Jquery Ajax调用,不会调用成功或错误
可能重复:
如何从函数中返回AJAX调用的响应?
我正在使用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 abc = new List(); //abc.Add(new IDName { Name=1, value="Success" }); return "Success"; } catch (Exception ex) { throw new Exception(ex.Message); } }
该服务正在从AJAX成功调用。 价值也在变化。 但是在服务之后, 成功:或者错误:函数没有被调用 ,在这种情况下,应该已经调用了成功但是它不起作用。
我使用了firebug,发现成功或错误函数被跳过并直接return Success;
似乎无法找到代码的问题。
提前致谢
更新:添加async: false
修复问题
将您的代码更改为
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调用默认是异步的。 因此,当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);
尝试将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对象的更多信息