我从 python 服务器收到一个 json 文件,我尝试使用 ajax 解析该文件,以根据单独的下拉菜单中的类别(例如 data_provider、census)显示值。但我不断收到以下错误: 未捕获错误:语法错误,无法识别的表达式:[{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"h1","summ_level":"160"},{"data_provider":"人口普查","data_year":"2010","data_series":"sf1","tb_name":"p1","summ_level":"050"}]
请帮帮我!下面是我写的代码。
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function codeAddress() {
var ajax = $.ajax({
//data : params,
type : "GET",
crossDomain: true,
dataType: "json",
//jsonp: "callback",
//callbackParameter: "callback",
//contentType : "application/x-www-form-urlencoded",
url : "http://0.0.0.0:8080/"
});
ajax.done(function() {
var response=ajax.responseText;
var json = jQuery.parseJSON(response);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
});
ajax.fail(function() {
alert("fail");
});
ajax.always(function() {
alert("done");
});
}
</script>
</head>
<body id="b1" onload="codeAddress();">
</body>
</html>
最佳答案
因为您将 datatype
设置为 json
,所以我猜您不需要自己解析 JSON。请注意,已解析的响应在 done
方法的第一个参数中提供,请参阅 jQuery 文档中的示例:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
})
.done(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
关于javascript - 使用ajax解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051674/