如何从AJAX请求中返回值?

Ale*_*olo 0 javascript 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
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 9

AJAX请求是异步的.您的sendRuest函数正在被执行,正在进行AJAX请求,但它是异步发生的; 所以在执行AJAX请求(和你的onreadystatechange处理程序)之前执行sendRuest的剩余部分,因此the_variable在返回它时是未定义的.

实际上,您的代码的工作方式如下:

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

     var the_variable;

     /* some code */

     return the_variable;
}

var data = sendRequest(someargums);
Run Code Online (Sandbox Code Playgroud)

然后一段时间后,您的AJAX请求正在完成; 但现在已经太晚了

你需要使用一个叫做回调的东西:

你以前可能有过的地方

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

  // do something;
}
Run Code Online (Sandbox Code Playgroud)

你应该做:

function () {
  sendRuest(args, function (theResult) {
     // do something
  });
};
Run Code Online (Sandbox Code Playgroud)

并修改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
        }
}
Run Code Online (Sandbox Code Playgroud)