我有一个函数x1,它具有对服务器的ajax调用,如下所示
var result;
function x1()
{
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
success: function (msg) {//On Successfull service call
result = msg.GetUrlContentResult;
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
我有另一个函数x11,它调用x1,它依赖于变量result的这个值,即全局变量。
function x11()
{
x1();
if (result==something)
{do something}
}
问题是因为x1()是异步函数,所以当执行if结果时,不会设置结果。我想我必须做一些类型的回调,看一些回调的例子我对这个有什么新的帮助如何正确设置一个回调所以当从x1返回时设置结果的值?我有多个调用x1()
的函数答案 0 :(得分:3)
单个ajax调用可以有多个成功处理程序。从x1()
返回jqXHR
object,并使用.done()
method从success
绑定其他x11()
处理程序:
function x1()
{
return $.ajax({
...
});
}
function x11()
{
x1().done(function(msg) {
// this is an additional success handler
// both handlers will be called
});
}
答案 1 :(得分:2)
你要做的事实上就像这样简单:(为动态回调编辑)
function x1(callback)
{
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
x1(x11);
您必须修改x11函数以接受msg
参数并更新result
变量:
function x11(msg) {
result = msg.GetUrlContentResult;
//...
}