从AJAX中的onreadystatechange事件返回值 [英] Returning values from the event onreadystatechange in AJAX
问题描述
我正在尝试在下面的代码中为变量val
分配一个值:
I am trying to assign a value to the variable val
in the code below:
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{
}
};
}
我在Firebug中跟踪变量,结果证明val
被分配了该功能.有没有办法让代码运行,然后将值分配给变量val
?
I was tracking the variables in Firebug and it turns out that val
gets assigned the function. Is there a way to get the code to run through and then assign the value to the variable val
?
推荐答案
在异步编程中,您不要 return
数据,因为您不知道何时该数据将变得可用-它是异步.
In asynchronous programming you do not return
data because you don't know when that data is going to become available - it's asynchronous.
进行异步编程的方法是使用事件和/或回调.
The way to do asynchronous programming is using events and/or callbacks.
示例:
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{
}
};
}
这个问题是关于SO的最常见问题之一,至少在涉及javascript标签时-请在问自己的问题之前先搜索类似的问题.
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.
这篇关于从AJAX中的onreadystatechange事件返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!