如何在AJAX中处理JSON输出?

我在.js文件中有这段代码片段

$(function () { // KeyDates var url = "http://localhost:8732/Design_Time_Addresses/Intel.IIP.MDF.WCF/ProgramCalendarService/GetKeyDatesCalendarNew"; $.ajax({ url: url, data: null, type: 'POST', contentType: 'application/json', dataType: 'json', success: function (GetKeyDatesCalendarDataNew) { alert(GetKeyDatesCalendarDataNew); $(document).ajaxStop($.unblockUI); } }); }); 

如何处理GetKeyDatesCalendarDataNew中的键值对?

您可能想知道如何访问对象的道具。 为此,使用for in循环迭代对象的值:

 success: function (GetKeyDatesCalendarDataNew) { for(var key in GetKeyDatesCalendarDataNew) { var value = GetKeyDatesCalendarDataNew[key]; // do somehitng based on the key and/or value iterated } } 

对于这种情况,success函数的参数是从Ajax请求返回的已评估JSON。 因此,您应该重命名为类似data GetKeyDatesCalendarDataNew将成为服务器返回的实际数据。

如果您知道其结构,则只能处理数据。 知道这一点的一个简单方法是执行console.log(GetKeyDatesCalendarDataNew) ,然后使用for循环轻松处理它,如果它是一个数组或者for x in..如果它是一个对象。

你可以使用JQuery“getJSON”函数,你需要传递url并指定一个回调函数。你的ajax调用将由getJSON函数处理。 在回调函数中,您可以访问Keys作为属性。 一个很好的例子

Lav G.

 $.each(GetKeyDatesCalendarDataNew,function(key,value){ //do something here })