使用ajax解析json

时间:2014-02-26 19:45:38

标签: javascript html ajax json

我从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>

2 个答案:

答案 0 :(得分:2)

因为您将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 ) );
});

答案 1 :(得分:0)

如果你已经在使用jQuery,那就让他们为你做一些笨拙的工作吧!

$.getJSON("http://0.0.0.0:8080/", function(json){
// do your JSON work here
});

如果由于某种原因您无法在$ .ajax请求中使用$ .getJSON,请设置一个success回调函数,就像我在这里的那个。