javascript 从 AJAX 中的 onreadystatechange 事件返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19298112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:03:36  来源:igfitidea点击:

Returning values from the event onreadystatechange in AJAX

javascriptjqueryajax

提问by Superios

I am trying to assign a value to the variable valin the code below:

我正在尝试为val以下代码中的变量赋值:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;

function what(){
    val = update('#TAG#');
}


function update(tag) {
    var req1 = newXMLHttpRequest();
    req1.open("GET",cmdValue + tag, true);
    req1.send("");

    return req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            return returned_data;
        }else{

        }
    };
}

I was tracking the variables in Firebug and it turns out that valgets assigned the function. Is there a way to get the code to run through and then assign the value to the variable val?

我正在跟踪 Firebug 中的变量,结果发现val分配了该函数。有没有办法让代码运行,然后将值分配给变量val

回答by Adam

In asynchronous programming you do notreturndata because you don't know when that data is going to become available - it's asynchronous.

在异步编程中,您不需要return数据,因为您不知道该数据何时可用 - 它是异步的。

The way to do asynchronous programming is using events and/or callbacks.

进行异步编程的方法是使用事件和/或回调。

Example:

例子:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;
var performSomeAction = function(returned_data) {
    val = returned_data;
}

function what(){
    update('#TAG#',performSomeAction);
}



function update(tag,callback) {
    var req1 = newXMLHttpRequest();
    req1.open("GET",cmdValue + tag, true);
    req1.send("");

    req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            //fire your callback function
            callback.apply(this,[returned_data]);
        }else{

        }
    };
}

This question is one of the most commonly asked questions on SO, at least when it comes to the javascript tag - please search for similar questions before asking your own.

这个问题是 SO 上最常见的问题之一,至少在涉及 javascript 标签时 - 请在提出自己的问题之前搜索类似的问题。

回答by Undercover

// should have a space after new or was did u notice it 
var req1 = new XMLHttpRequest();