可能重复:
How to return the response from an AJAX call from a function?
我正在使用Jquery Ajax来调用服务来更新值。
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
Success = false;//doesnt goes here
}
});
//done after here
return Success;
}
和服务:
[WebMethod]
public string SavePurpose(int Vid, int PurpId)
{
try
{
CHData.UpdatePurpose(Vid, PurpId);
//List<IDName> abc = new List<IDName>();
//abc.Add(new IDName { Name=1, value="Success" });
return "Success";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
该服务正在从AJAX成功调用。 价值也在改变。但在服务之后,成功或错误功能未被调用,在这种情况下,应该已经调用了成功,但它无效。
我使用了firebug并发现成功或错误函数被跳过并直接转到return Success;
似乎无法找到代码的问题。
提前致谢
更新
添加async: false
解决了问题
答案 0 :(得分:29)
将您的代码更改为
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async:false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
Success = false;//doesnt goes here
}
});
//done after here
return Success;
}
您只能从synchronous
函数返回值。否则,您必须制作callback
。
所以我刚刚将async:false,
添加到您的ajax调用
<强>更新强>
jquery ajax调用默认是异步的。如此成功&amp;当ajax加载完成时,将调用错误函数。但是你的return语句将在ajax调用开始后执行。
更好的方法
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
并将ajax称为
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
答案 1 :(得分:10)
尝试将ajax调用封装到函数中,并将async选项设置为false。请注意,自jQuery 1.8以来不推荐使用此选项。
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
您也可以这样做:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
您可以阅读有关jqXHR jQuery Object
的更多信息