纯js获取url json/jsonp数据,支持主流浏览器和手机浏览器
// 获取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); }
); 相关推荐
86193952 2020-10-27
小木兮子 2020-11-11
seanzed 2020-10-15
huangliuyu00 2020-09-24
libaoshan 2020-09-11
zhangpan 2020-09-10
chongxiaocheng 2020-08-16
xcguoyu 2020-08-15
Qizonghui 2020-08-02
ldcwang 2020-07-26
mqfcu 2020-07-21
jeason 2020-07-20
sunzhihaofuture 2020-07-19
knightwatch 2020-07-19
点滴技术生活 2020-07-19
Reiki 2020-07-06