使用jQuery / AJAX解码JSON

我正在尝试使用jQuery解码 JSON.
这是我得到的(例如一个班级,这里有一个学生):
"{"Students":[{"Name":John,"Grade":17,}],"TotalClass":17,"TotalCount":1,}"

这是我的所作所为:

$j.ajax({
    type: 'POST',url: 'class.aspx/getClass',contentType: 'application/json; charset=utf-8',dataType: 'json',success: function (msg) {
        $j.each(msg,function (index,element) {
            alert(element.TotalClass);
        });
    },});

它一直在警告中说未定义(但我收到了正确的JSON).知道我做错了什么吗?

解决方法

{"Students":[{"Name":John,}

是无效的JSON!

假设你有一个像这样的有效JSON

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

您可以像这样访问这些值

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

工作样本:http://jsfiddle.net/ncbLF/5/

使用jsonlint验证JSON

所以你的代码可以简化为

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

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...