jQuery:循环遍历ASP.NET webservice的JSON结果

时间:2012-06-01 10:53:43

标签: jquery asp.net json web-services

我有一个返回JSON的ASP.NET Web服务。现在,使用jQuery我想调用这个webservice然后循环结果。但是如何?

我现在有了这个:

jQuery.support.cors = true;
$().ready(function () {
    $.ajax({
        type: "GET",
        url: "http://www.wunderwedding.com/weddingservice.svc/api/?t=1&cid=1&pid=6&lat=52&lng=5&d=10000&city=nijmegen&field1=0&field2=0&field3=0&field4=0&hasphoto=0&hasvideo=0&minrating=0&lang=nl",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Hide the fake progress indicator graphic.
            $('#mytest').removeClass('loading');
            alert(msg.d);
            // Insert the returned HTML into the <div>.
            $('#mytest').html(msg.d);
        }
    });

2 个答案:

答案 0 :(得分:1)

假设你的web方法正在返回一个人的数组,所以在成功的方法中你可以循环遍历它:

$.each(msg.d.Persons, function(index, Value)
{
      firstName = msg.d.Persons[index].FirstName;
});

答案 1 :(得分:-1)

如果你的webservice返回一个JSON,那么最好解析它。

假设你的json是这样的:

{
    "Status": "ok",
    "Persons": [
        {
            "Name": "John"

        },
        {
            "Name": "Louis"
        }
    ]
}

 success: function (msg) {
        var obj = JSON.parse(msg);

        //get the status value:
        var status = obj.Status;

        //Loop through Persons array:
        var names = {};
        $.each(obj.Persons, function (index, Person) {
            names[index] = Person.Name;
        });


    }

要使用JSON.parse(),您可能需要:

https://github.com/douglascrockford/JSON-js/blob/master/json2.js