小编典典
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
1500

被折叠的 条评论
为什么被折叠?



