在更改页面之前调用ajax?

示例代码:

$.ajax({ url: someUrl, data: someData, dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", success: function () { }, }); window.location = urlToGoTo; 

可以说上面的代码在用户单击按钮时运行。

由于ajax调用是异步的,当上面的代码运行时会发生什么? 使用像Fiddler这样的工具,看起来有时ajax调用成功,有时它永远不会被调用(即当前的网页在ajax调用有机会运行之前被更改)。

在这种情况下,您是否应该在设置window.location之前等待ajax调用完成(例如在ajax“完成”事件中)?

试着深入了解幕后发生的事情。

您可以在成功回调中进行重定向

 $.ajax({ url: someUrl, data: someData, dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", success: function () { window.location = urlToGoTo; } }); 
  • 如何从异步调用返回响应?

您必须在ajax调用中包含重定向链接代码,尤其是在success函数内:

  $.ajax({ url: someUrl, data: someData, dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", success: function () { window.location = urlToGoTo; }, error:function(){ alert("Error Occurred!"); } });