Javascript 将参数传递到ajax onreadystatechange回调?
将参数传递到匿名onreadystatechange回调的普通纯javascript(即非JQuery)方式是什么 例如:Javascript 将参数传递到ajax onreadystatechange回调?,javascript,ajax,Javascript,Ajax,将参数传递到匿名onreadystatechange回调的普通纯javascript(即非JQuery)方式是什么 例如: function doRequest(){ /* Get an XMLHttpRequest in a platform independent way */ var xhttp = getXmlHttpRequestObject(); var msg="show this message when done"; /* another v
function doRequest(){
/* Get an XMLHttpRequest in a platform independent way */
var xhttp = getXmlHttpRequestObject();
var msg="show this message when done"; /* another variable to pass into callback */
/* How do I pass 'msg' and 'xhttp' into this anonymous function as locals
named 'x' and 'm'??? */
xhttp.onreadychangestate=function(x,m)
{
if( x.readyState == 4 )
{
alert(m);
}
}
/* do the open() and send() calls here.... */
}
Javascript支持闭包,因此您编写的匿名函数将能够从封闭的
doRequest()
范围访问xhttp
和msg
如果希望显式地执行此操作(例如,如果希望在代码中的其他地方定义回调函数并重用它),则可以创建一个创建回调的函数。这还允许您使用不同的名称(如x
和m
)来别名变量:
然后在doRequest()
中,执行xhtp.onreadystatechange=createCallback(xhtp,msg)代码>
如果您只想“重命名”变量,则可以内联匿名执行此操作:
xhttp.onreadystatechange = (function(x, m) {
return function() {
/* Do stuff */
}
})(xhttp, msg);
上面的部分答案对我不起作用。首先,对于没有参数的单独回调函数:
xhttp.onreadystatechange = callBack; //works; the function's NAME is required
xhttp.onreadystatechange = callBack(x,m); //didn't work, and didn't know why
xhttp.onreadystatechange = createCallback(xhttp,msg); //bad part of above Answer
现在假设修改回调函数以接收一些参数:
xhttp.onreadystatechange = callBack; //works; the function's NAME is required
xhttp.onreadystatechange = callBack(x,m); //didn't work, and didn't know why
xhttp.onreadystatechange = createCallback(xhttp,msg); //bad part of above Answer
然而,在StackOverflow的其他地方,有人解释说,这与需要为onreadystatechange分配“函数引用”而不是“函数调用”有关(就像上面的名称是函数引用),并发布了一个解决方案:
xhttp.onreadystatechange = function(){callBack(x,m);}; //works
我来这里是想给另一个答案添加一些东西,但现在找不到了。所以我不妨把它加在这里。在我自己的代码中,我同时使用了局部变量和全局变量,发现了一些似乎不正确的地方,但现在我知道实际发生了什么,一句警告似乎是合适的。假设“g”是一个全局变量:
xhttp.onreadystatechange = function(){callBack(x,g);};//anonymous function works
函数引用在某个时间点(T0)分配给onreadystatechange,回调函数在不同的时间(T1)调用。好的,全局变量“g”在T1的值是传递给回调函数的值,而不是在T0分配函数引用时的“g”值。别让它咬了你,就像它咬了我一样!(局部变量通常没有这个问题,因为它们通常在T1超出范围,所以JavaScript在设置匿名函数的参数值时,必须在T0使用它们的现有值。)永远不会太晚!:-)
与使用xhttp.onreadystatechange中的参数传递数据(这有点复杂)不同,只需向xhr对象本身添加属性即可
例如:
var m = "Hello!";
var xhttp = new XMLHttpRequest();
xhttp.m = m;
xhttp.onreadystatechange = function()
{
var x, m;
x = this;
m = x.m;
if ((x.readyState == 4) && (x.status == 200))
{
alert(m);
}
};
// ...
谢谢这个答案促使我对Javascript有了更多的了解。实际上,我只需要知道闭包是如何工作的。http.onreadystatechange=function(){var xmlHttp=this;if(xmlHttp.status==200){console.log(“我们得到了!”);};这对我有用。我将回调函数添加到新的XMLHttpRequest中。我想说清楚。说“myXMLHttpRequest.anythingIWant=anything”是非常安全的;它只会记住那个值?@Joe C yes,“myXMLHttpRequest.anythingIWant”值是“anything”,只要“myXMLHttpRequest”存在,包括在回调函数中。这对我来说是有效的。与此相反,直接使用变量xhr.value=response;在onreadystatechange函数中,通过xhr.value访问它