简体   繁体   English

使用ajax解析json

[英]Parse json using ajax

I receive a json file from a python server, which I try to parse using ajax to display the values according to the categories(egdata_provider,census) in separate drop down menus .But i constantly get the following error: Uncaught Error: Syntax error, unrecognized expression: [{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"h1","summ_level":"160"},{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"p1","summ_level":"050"}] 我从python服务器收到一个json文件,我尝试使用ajax在单独的下拉菜单中根据类别(egdata_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”}]

Kindly help me out ! 请帮助我! Below is the code I wrote. 以下是我写的代码。

<!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>

Because you're setting datatype to json , I'd guess you do not need to parse the JSON yourself. 因为你将datatype设置为json ,我猜你不需要自己解析JSON。 Please note that the parsed response is provided in the done method's first argument, see this example from the jQuery docs: 请注意,解析的响应在done方法的第一个参数中提供,请参阅jQuery文档中的此示例:

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
})
.done(function( data ) {
  console.log( "Sample of data:", data.slice( 0, 100 ) );
});

If you're already using jQuery, just let them do the grunt work for you! 如果你已经在使用jQuery,那就让他们为你做一些笨拙的工作吧!

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

If for whatever reason you can't use $.getJSON, in your $.ajax request, set a success callback function like the one i have over here. 如果由于某种原因你不能在$ .ajax请求中使用$ .getJSON,请设置一个success回调函数,就像我在这里的那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM