Decode JSON with jQuery / AJAX

与世无争的帅哥 提交于 2019-12-05 05:18:04
{"Students":[{"Name":John,"Grade":17,}],"TotalClass":17,"TotalCount":1,}

is not valid JSON !

Assuming you have a valid JSON like this

{
    "Students": [
        {
            "Name": "John",
            "Grade": "17"
        }
    ],
    "TotalClass": " 17",
    "TotalCount": "1"
}

You can access the values like this

alert("TotalClass : "+msg.TotalClass);
//loop thru students
$.each(msg.Students,function(index,item){
   alert(item.Name+ " - "+item.Grade)
}); 

Working sample : http://jsfiddle.net/ncbLF/5/

Use jsonlint to validate JSON

So your code can be simplified to

$.getJSON("class.aspx/getClass",function(msg){

    alert("TotalClass : "+msg.TotalClass);
    $.each(msg.Students,function(index,item){
        alert(item.Name+ " - "+item.Grade)
    });
});

contentType is the type of the data sent to the server, not from. Remove that.

The JSON you included in the question. Is that the exact JSON the server returns? Because if it is, you don't need the $.each. You have an object, you should only need $.each to loop though an array of objects.

So, just try alert(msg.TotalClass).

Also, that JSON is invalid. You have an extra , after TotalCount, and after Grade. Also, John should be in double quotes.

Just try to alert

$j.each(msg, function (key, element) {
    alert(key); // output: Students, TotalClass..
    alert(element); //output: [{"Name":John,"Grade":17,}, 17..
});

Note

as you set dataType: 'json' so I think you don't need any additional parse effort and given JSON has error, don't know is it your written or originally sent from server.

And you don't need the line

contentType: 'application/json; charset=utf-8',

You valid json should look like:

{
    "Students": [
        {
            "Name": "John",
            "Grade": "17"
        }
    ],
    "TotalClass": " 17",
    "TotalCount": "1"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!