简体   繁体   English

ajax json 解析错误

[英]ajax json parsing error

json : {"status" : 0, "err_msg": "", "list":[{"id":100, "username":"la", num:"0100000"}]}

<script>
$.ajax({
type : "POST",
    url : "myAPI",
    data: "{ \"offset\" : 0, \"limit\" : 10 }",
    dataType : "json",
    success : function(json) {
    var message_list = json.list;
    var list_count = message_list.length;
    $.each(list_count, function() {
        var message_id = message_list.id;
        var message_username = message_list.username;
        var message_num = message_list.num;

        var html = "<tr>";
        html += "<td>"+message_id+"</td>";
        html += "<td>"+message_username+"</td>";
        html += "<td>"+message_num+"</td>";
        html += "</tr>";

        $("#tablebody").append(html);
        });
    },
    error: function() {
        alert("에러");
    }
});
</script>

please fix an error I want go success:(请修复一个错误我想成功:(

The json should look like this: json 应如下所示:

{
    "status": 0,
    "err_msg": "",
    "list": [
        {
            "id": 100,
            "username": "la",
            "num": "0100000"
        }
    ]
}

Notice the num has also double quotes If you defined dataType json then you are waiting from server API a json type object if you get a parse error make sure you are getting an object json from API.请注意 num 也有双引号 如果您定义了 dataType json 那么您正在等待来自服务器 API 的 json 类型对象 如果您收到解析错误,请确保您从 API 获取对象 json。

If the json returned is the one comming from server it should be a valid one.如果返回的 json 是来自服务器的 json,则它应该是有效的。

You are using $.each not properly.您使用的$.each不正确。

var message_list = json.list; // array
var list_count = message_list.length; // length 
$.each(list_count, function() { // why do you call `$.each(length)`?
    var message_id = message_list.id; // why do you call array.id?
    var message_username = message_list.username;
    var message_num = message_list.num;

    var html = "<tr>";
    html += "<td>"+message_id+"</td>";
    html += "<td>"+message_username+"</td>";
    html += "<td>"+message_num+"</td>";
    html += "</tr>";

        $("#tablebody").append(html);
        });
    }

It should be:它应该是:

var message_list = json.list; // array

$.each(message_list, function() { // $.each(array)
    var message_id = this.id; // "this" context - is an item
    var message_username = this.username;
    var message_num = this.num;

    var html = "<tr>";
    html += "<td>"+message_id+"</td>";
    html += "<td>"+message_username+"</td>";
    html += "<td>"+message_num+"</td>";
    html += "</tr>";

    $("#tablebody").append(html);
});

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

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