【问题标题】:Simple XMLHttpRequest function to return a JSON object返回 JSON 对象的简单 XMLHttpRequest 函数
【发布时间】:2015-05-31 05:39:03
【问题描述】:

我试图在 XMLHttpRequest 获取请求之后返回一个 json 对象,但我做不到。我认为这可能是因为它是异步的,但我真的不知道如何使它工作。我做错了什么?

$(document).ready(function() {

var apiEndpoint = 'http://someapiendpoint.com/'

//Helpers
function sendRequest(_path) {
  var results =  {}
  req = new XMLHttpRequest()
  req.open('GET', apiEndpoint+_path)
  req.onreadystatechange = function() {
    if (this.readyState === 4) {
      results = JSON.parse(this.response)
    }
  }
  req.send()
  return results
}

// Action
console.log(sendRequest('client1/'))

}); // end document ready

【问题讨论】:

  • 异步调用伙伴,console.log只会得到你{}
  • 嗯好吧,所以如果我这样做req.open('GET', apiEndpoint+_path, false) 它可以工作......但我想这也会阻止执行,对吧?
  • 你正在尝试返回尚未准备好的结果

标签: javascript jquery json xmlhttprequest


【解决方案1】:

你应该使用这个结构

function sendRequest(_path, cb) {
    req = new XMLHttpRequest()
    req.open('GET', apiEndpoint+_path);
    req.onreadystatechange = function() {
    if (this.readyState === 4) {
        cb(JSON.parse(this.response));
    }
    else{
        cb(null);
    }
}
    req.send();
}

// Action
sendRequest('client1/', function(result){
    console.log(result);
})

对于异步调用,您需要使用回调

【讨论】:

【解决方案2】:

由于您已经在使用 jQuery,您可以执行以下操作:

$(document).ready(function() {
   var apiEndpoint = 'http://someapiendpoint.com/';

   function sendRequest(path, callback){
      $.get(apiEndpoint+path, function(response){
          callback(JSON.parse(response));
      }, json).fail(function(){
          console.log('Failed');
      });
   }

   sendRequest('client1/', function(json){
       if(json){
           console.log(json);
       }
   });
});

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2017-09-17
    • 2017-06-25
    • 2021-08-24
    • 2012-12-20
    • 2021-06-09
    相关资源
    最近更新 更多