// 获取json数据,目前主流浏览器和手机浏览器都兼容 var getJSON = function(url, type) { type = type || 'get'; return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(type, url, true); xhr.responseType = 'json'; xhr.onload = function() { var status = xhr.status; if (status == 200) { resolve(xhr.response); } else { reject(status); } }; xhr.send(); }); };
// 我们这样使用 getJSON('/forum.php?mod=hot&page=' + page).then(function(data) { // Do something you want }, function(status) { console.log('Something went wrong, status is ' + status); });
// 获取jsonp数据我们可以这样 function insertReply(content) { document.getElementById('output').innerHTML = content; } // create script element var script = document.createElement('script'); // assing src with callback name script.src = 'http://url.to.json?callback=insertReply'; // insert script to document and load content document.body.appendChild(script);
//如果上面的不支持,说明浏览器没有promise对象,可使用callback的方式:
var getJSON = function(url, success, error) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { if (success) success(JSON.parse(xhr.responseText)); } else { if (error) error(xhr); } } }; xhr.open('GET', url, true); xhr.send(); }; loadJSON('my-file.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); } );