使用jQuery / AJAX德code JSON [英] Decode JSON with jQuery / AJAX

查看:112
本文介绍了使用jQuery / AJAX德code JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图去code使用jQuery的JSON。 下面是我得到(例如一类,这里一个学生):

 {学生:[{姓名:约翰,等级:17}],TotalClass:17,TotalCount:1,}
 

这是我做的:

  $ j.ajax({
    键入:POST,
    网址:class.aspx /的getClass',
    的contentType:应用/ JSON的;字符集= UTF-8,
    数据类型:JSON,
    成功:函数(MSG){
        $ j.each(味精,功能(索引,元){
            警报(element.TotalClass);
        });
    },
});
 

它口口声声说未定义的警报(但我收到正确的JSON)。知不知道我做错了什么?

解决方案

  {学生:[{姓名:约翰,等级:17}],TotalClass :17,TotalCount:1,}
 

是不是有效的JSON!

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

  {
    学生:
        {
            名:约翰,
            等级:17
        }
    ]
    TotalClass:17,
    TotalCount:1
}
 

您可以访问值,像这样

 警报(TotalClass:+ msg.TotalClass);
//环通学生
$每个(msg.Students,函数(指数,项目){
   警报(item.Name + - + item.Grade)
});
 

工作示例: http://jsfiddle.net/ncbLF/5/

使用 jsonlint 验证JSON

所以,你的code可以简化为

  $。的getJSON(class.aspx /的getClass,函数(MSG){

    警报(TotalClass:+ msg.TotalClass);
    $每个(msg.Students,函数(指数,项目){
        警报(item.Name + - + item.Grade)
    });
});
 

I'm trying to decode a JSON with jQuery. Here's what I get (for instance a class, here with one student):

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

here's what I do:

$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);
        });
    },
});

It keeps saying undefined in the alert (but I recieve the right JSON). Any idea what I'm doing wrong?

解决方案

{"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)
    });
});

这篇关于使用jQuery / AJAX德code JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆