从包含AJAX函数的JavaScript文件返回数据

Returning data from JavaScript file that contains AJAX function

本文关键字:文件 返回 数据 JavaScript 包含 AJAX 函数      更新时间:2023-09-26

我已经创建了control.js文件,其中包含向服务器发送POST和GET请求的AJAX函数。

问题是,我无法返回我从control.js文件中的AJAX函数接收到的数据到其他javascript文件。

我明白我们不能直接从异步函数返回数据。它需要额外的函数来处理从函数返回的数据。

 function getServer(directory)
    {
        xmlHttp.open("GET",rootDirectory+directory);
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState == 4)
            {
                if(xmlHttp.status == 200)
                {
                    Handler(xmlHttp.responseText);
                }
            }
        };
        xmlHttp.send();
    }
 function Handler(response)
 {
      return response;
 }

函数处理程序将数据正确地返回到其自己的文件(在control.js文件中)中的每个函数调用。

现在,假设我有多个JavaScript文件,并且我想调用这个函数。我怎么能得到从这个文件中的函数返回的值?

的例子:

function construct()
{     
    // This function belongs to load.js file not control.js
    var handler = getServer("request/read.php?table=tasks");        
    console.log(handler);  // This one return nothing...//
}

Handler函数作为参数传递,而不是将其硬编码到函数中。

getServer("/foo/bar/", myFunction);