How to process JSON output in AJAX?

2019-09-02 11:57发布

I have this code snippet in .js file

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

});

How do i process the key value pair in GetKeyDatesCalendarDataNew?

4条回答
ら.Afraid
2楼-- · 2019-09-02 11:59

You probably want to know how to access an object's props. For that, use the for in loop to iterate over the object's values:

success: function (GetKeyDatesCalendarDataNew) {
   for(var key in GetKeyDatesCalendarDataNew)
       {
           var value = GetKeyDatesCalendarDataNew[key];
           // do somehitng based on the key and/or value iterated
       }
}
查看更多
爷的心禁止访问
3楼-- · 2019-09-02 12:19

For this case, the argument of the success function is the evaluated JSON that was returned from the Ajax request. Therefore GetKeyDatesCalendarDataNew, which you should rename to something like data, becomes the actual data that your server returned.

You can only process the data if you know its structure. One simple way of knowing this would be to do console.log(GetKeyDatesCalendarDataNew) and then easily process it with a for loop if it's an array or for x in.. if it's an object.

查看更多
Animai°情兽
4楼-- · 2019-09-02 12:20

You can use JQuery "getJSON" function where you need to pass the url and specify a callback function.Your ajax call will be handled by the getJSON function. In the callback function, you can access the Keys as properties. A nice example

Lav G

查看更多
【Aperson】
5楼-- · 2019-09-02 12:22
$.each(GetKeyDatesCalendarDataNew,function(key,value){
    //do something here
})
查看更多
登录 后发表回答