从ajax请求返回值到另一个函数 [英] return value from ajax request to another function
问题描述
我正在尝试从(传输)向调用函数返回一个值,但似乎无法让它工作:
I'm trying to return a value from (transport) to the calling function, but can't seem to get it to work:
function createXMLHttpRequest( w )
{
var urly = '/users/notes/' + w;
var options = {
method:'get'
, onSuccess: function( transport )
{
x = transport.responseText;
return x;
}
, onFailure: function( transport )
{
var response = transport.responseText;
alert( "FAILED "+ response );
}
};
new Ajax.Request( urly, options );
alert( x );
}
var ai = $( 'addItem' );
ai.onclick = function()
{
// -1 indicates new
addnote( -1, null );
}
x
总是提示未定义.除非我将 x
分配给 Ajax.Request
例如x=new Ajax.Request(url,options)
.然后它会提醒[Object object]
.如何将 transport.responseText
的值返回给 onclick
函数?
x
always alerts undefined. Unless I assign x
to the Ajax.Request
e.g. x=new Ajax.Request(urly,options)
. It then will alert [Object object]
. How can I return the value of transport.responseText
to the onclick
function?
推荐答案
您的请求不是 asynchronous:false
.所以在请求完成之前 x 会收到警报,并且 x
被设置为 transport.responseText
.
Your Request is not asynchronous:false
. So x is alerted before the request is completed and x
is set to transport.responseText
.
您必须将请求设置为同步请求,或者在 onSuccess
方法中提醒 x.
You have to either set the request as synchronous, or alert x in the onSuccess
method.
onSuccess 的返回值被 Ajax.Request 丢弃.不要返回任何东西.
The return value from onSuccess is discarded by Ajax.Request. Don't return anything.
Ajax 本质上是异步的.您应该查询服务器,然后在回调中处理响应.因此,您不应尝试在 onclick 函数中使用服务器值,而应在单独的回调(onSuccess 方法)中使用.
Ajax is asynchronous by nature. You should query the server, then handle the response in a callback. So you should not try to use the server value in the onclick function, but rather in a separate callback (the onSuccess method).
这篇关于从ajax请求返回值到另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!