Let’s first take the JSON data parsing the comments object in the above example as an example, and then summarize the method of parsing JSON data in jQuery.
The JSON data is as follows, which is a nested JSON:
To get JSON data, there is a simple method $.getJSON() in jQuery.
The following is the official API description of $.getJSON():
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.
The callback function accepts three parameters. The first is the returned data, the second is the status, and the third is jQuery's XMLHttpRequest. We only use the first parameter.
$.each() is a method used to parse JSON data in the callback function. The following is the official document:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
collectionThe object or array to iterate over.
callback(indexInArray, valueOfElement)The function that will be executed on every object.
The $.each() method accepts two parameters. The first is the object collection that needs to be traversed (JSON object collection). The second is the method used to traverse. This method accepts two parameters. The first is the traversed index, and the second one is the current traversed value. Haha, with the $.each() method, JSON parsing is easily solved. (*^__^*) Hee hee...
The results of the above example are as follows:
If the returned JSON data is more complex, just use more $.each() to traverse it, hehe. For example, the following JSON data:
It is worth noting that when $.each() traverses the Map, the parameters in function() are key and value, which is very convenient.