jsonp needs to add a <script> element to the page, which is used to load json data from other servers.
< body > < script src ="js/jsonp.js?callback=showEvents" ></ script > //The file obtained from the server, add the attributes you want to get after the URL </ body >
The web browser itself needs a function to handle json
//This function is specially used to process json data, data is the obtained json object
function showEvents(data) { var newContent = '' ; for ( var i = 0; i < data.events.length; i++ ){ newContent += '<div class="date">'; newContent += '<div class="image"><img src="' + data.events[i].map +'"></div>'; newContent += '<p>' + data.events[i].location + '</p>'; newContent += '<span>' + data.events[i].date + '</span>'; newContent += '</div>'; } document.getElementById('box').innerHTML = newContent; }
Because the data is a script file returned by script, it will be regarded as an object, and the parse and stringify methods of JSON are not needed.
// <script src="js/jsonp.js?callback=showEvents"></script> incoming file
showEvents({ "events" : [ { "location" : "San Francisco, CA", "date" : "May 1", "map" : "img/001.jpg" }, { "location" : "Austin, TX", "date" : "May 15", "map" : "img/002.jpg" }, { "location" : "New York, NY", "date" : "May 30", "map" : "img/003.jpg" } ] });