`

纯js获取url json/jsonp数据,支持主流浏览器和手机浏览器

    博客分类:
  • js
阅读更多
// 获取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); }
);

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics