2012-06-01 146 views
0

我有一個返回JSON的ASP.NET webservice。現在,使用jQuery我想調用這個web服務,然後循環結果。但是如何?jQuery:通過ASP.NET webservice的JSON結果循環

我現在有這樣的:

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

回答

1

可以假設你的Web方法是成功的方法返回的個人的數組,這樣你們可以遍歷它想:

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

好吧,但我張貼犯規的代碼似乎回到什麼。 您是否嘗試過我的代碼示例中列出的web服務? – Flo

+0

我檢查了它,聽起來工作正常,你唯一缺少的是你調用一個web服務出你的域,所以對於跨域調用,你需要包含以下行: jQuery.support.cors = true ; 把這一行放在前面: $()。ready(function(){ –

+0

我在我的第一篇文章中更新了代碼,但是在'alert'我得到'undefined' – Flo

-1

如果你的web服務返回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