return 一个 JSON 对象的简单 XMLHttpRequest 函数

Simple XMLHttpRequest function to return a JSON object

我试图在 XMLHttpRequest get 请求后 return 一个 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

你应该使用这个结构

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);
})

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

由于您已经在使用 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);
       }
   });
});