小编典典

如何从AJAX请求返回值?

ajax

我有一个函数,用var关键字声明一个变量。然后,它将启动AJAX请求以设置变量的值,然后从函数中返回此变量。

但是,我的实现失败了,我也不知道为什么。

这是代码的简化版本;

function sendRequest(someargums) {
     /* some code */

     var the_variable;

     /* some code */

     request.onreadystatechange = 
        //here's that other function    
        function() {                
            if (request.readyState == 4) {    
                switch (request.status) {
                    case 200:
                        //here the variable should be changed
                        the_variable = request.responseXML;

        /* a lot of code */

        //somewhere here the function closes
        }

     return the_variable;
}

var data = sendRequest(someargums); //and trying to read the data I get the undefined value

阅读 380

收藏
2020-07-26

共1个答案

小编典典

AJAX请求是异步的。您的sendRuest函数正在执行,正在发出AJAX请求,但它是异步发生的;因此,sendRuest的其余部分在AJAX请求(和onreadystatechange处理程序)执行之前就已执行,因此the_variable在返回时未定义。

有效地,您的代码如下工作:

function sendRuest(someargums) {
     /* some code */

     var the_variable;

     /* some code */

     return the_variable;
}

var data = sendRequest(someargums);

然后过了一段时间,您的AJAX请求已完成;但为时已晚

您需要使用一种称为回调的方法:

您以前可能曾经有过的地方

function () {
  var theResult = sendRuest(args);

  // do something;
}

你应该做:

function () {
  sendRuest(args, function (theResult) {
     // do something
  });
};

sendRuest进行如下修改:

function sendRuest(someargums, callback) {
     /* some code */

     //here's that other function 
     request.onreadystatechange =   
        function() {                
            if (request.readyState == 4) {    
                switch (request.status) {
                    case 200:
                        callback(request.responseXML);

        /* a lot of code */

        //somewhere here the function closes
        }
}
2020-07-26