JavaScript对象中的同步XMLHttpReqests

时间:2014-06-24 22:01:29

标签: javascript asynchronous xmlhttprequest standards synchronous

我使用以下JavaScript函数对象来处理对服务器的请求:

function Request(query, url) {
    var that = this;
    this.request = new XMLHttpRequest();
    this.response = ''; 

    this.set_response = function() {
        if (that.request.readyState==4 && that.request.status==200) {
            that.response = that.request.response;    
        }   
    }   

    this.request.onreadystatechange = this.set_response;
    this.request.open('POST', url, false); 
    this.request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    this.request.send(query);
}

有了这个对象,我可以这样做:

var needed_data = new Request('data=needed', 'serverside.php').response;

现在我需要从服务器获取的数据很好地存储在needed_data变量中(作为json编码的字符串)。问题是在主线程中使用同步请求已被弃用。我希望有人可以帮助我找到一种方法来达到相同的结果,同时符合标准。

2 个答案:

答案 0 :(得分:0)

你必须使它异步。

//allow to pass a callback
function Request(query, url, callback) {
    var that = this;
    this.request = new XMLHttpRequest();
    this.response = ''; 

    this.set_response = function() {
        if (that.request.readyState==4 && that.request.status==200) {
            that.response = that.request.response;
            callback && callback(that); //invoke the callback when data is available
        }   
    }   

    this.request.onreadystatechange = this.set_response;
    this.request.open('POST', url, true); //make the call async
    this.request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    this.request.send(query);
}

new Request('data=needed', 'serverside.php', function (request) {
    console.log(request.response);
});

答案 1 :(得分:0)

您应该从不在与应用程序其余部分相同的线程中使用同步XMLHttpRequest

function request(query, url, callback) {
  var xhr = new XMLHttpRequest();   
  xhr.open('POST', url, true);
  xhr.onreadystatechange = function(){
    if (xhr.readyState === 4 && xhr.status === 200 && callback) {
      callback(xhr.responseText);
    } 
  };
  xhr.send(query);
  return xhr;
}

request('data=needed', 'serverside.php', function(responseText){
  var needed_data = JSON.parse(responseText);
});