jsonp需要在页面中添加一个<script>元素,由该元素来从其他服务器加载json数据。
web浏览器本身需要一个处理json的函数
//这个函数专门用来处理json数据的,data是获取的json对象
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; }
因为数据是用script返回的脚本文件,所以会被视为对象,不需要JSON的parse和stringify方法了。
//<script src="js/jsonp.js?callback=showEvents"></script>传入的文件
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" } ] });