使用Jquery消耗json数据

时间:2013-07-24 03:32:11

标签: jquery json

我的.cs页面中有一个webMethod,它返回一个列表。

这会像这样返回json ..

{
    "d": [
        "Saint Clair",
        "Jefferson",
        "Shelby",
        "Tallapoosa",
        "Blount",
        "Talladega",
        "Marshall",
        "Cullman",
        "Bibb",
        "Walker",
        "Chilton",
        "Coosa",
        "Clay",
        "Tuscaloosa",
        "Hale",
        "Pickens",
        "Greene",
        "Sumter",
        "Winston"
    ]
}

我的jaquery方法是

   $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: StrUrl,
                data: "{'StateId':'" + Stateid + "'}",
                async: false,
                success: function (response) {
                    var obj = jQuery.parseJSON(response);
                    alert(obj.d[0]);

                }
            })

我想在Jquery中遍历这个json数据并获取json数据中的所有值。

4 个答案:

答案 0 :(得分:0)

jQuery有一个名为parseJSON()的内置方法,它接受一个字符串并返回一个Javascript对象。

Here is a link to the documentation

答案 1 :(得分:0)

使用.parseJSON()

var obj = jQuery.parseJSON('{"d":["Saint Clair","Jefferson","Shelby","Tallapoosa","Blount","Talladega","Marshall","Cullman","Bibb","Walker","Chilton","Coosa","Clay","Tuscaloosa","Hale","Pickens","Greene","Sumter","Winston"]}');
var p1 = obj.d;
for (var i = 0; i < p1.length; i++) {
    console.log(p1[i]);
}

选中此JSFiddle

更新:检查您是否遇到任何错误

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: StrUrl,
    data: "{'StateId':'" + Stateid + "'}",
    async: false,
    success: function (response) {
        var obj = jQuery.parseJSON(response);
        var p1 = obj.d;
        for (var i = 0; i < p1.length; i++) {
            console.log(p1[i]);
        }
    },    
       error: function(e){
            console.log("Error occured:" + e);
       }
});

答案 2 :(得分:0)

我认为你甚至不需要JQuery。

使用jquery拨打电话。现在,这里你的D是数组。所以,你需要向下一步才能获得阵列。

以下是示例代码

var jsn = //is your json you are getting from web method

jsn.d.forEach(function(a){
console.log(a); // here you are getting every element.
});

如果需要进一步的详细信息,请告诉我。

根据你的评论它没有用。这是工作jsfiddle的例子。我已经更新了一点点jquery来添加东西到dom。因此,您不必检查控制台。

答案 3 :(得分:0)

由于您从服务器获得了json响应,因此可以在ajax请求中使用dataType: 'json'。然后使用$.each()遍历数组

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: StrUrl,
    data: "{'StateId':'" + Stateid + "'}",
    async: false,
    dataType: 'json',
    success: function (response) {
        $.each(response, function(idx, value){
            alert(value)
        });
    }
})