Ajax与jQuery同步。 可能吗?

我在ajax.php页面中放了一个sleep(5)。 我需要返回的代码来启动另一个函数组。 它也使用ajax。 我的第一个ajax调用看起来像这样:

$.ajax({ url: '/ajax.php', data: { id : code } , type: 'POST', async:false, //<<< here cache: false, beforeSend: function(){ $('#loading').dialog(); }, success: function(data){ console.log(data.result); $('#loading').dialog('close'); initAnotherFunctionGrop(data.result); }, error: function(){ $('#loading').dialog('close'); } }); 

为什么我无法在IE和Chrome中显示加载消息? 只是Firefox正在使用它。

异步代码是最好的。 同步代码可能会挂起您的浏览器,这在ajax的情况下是一个坏主意,其中ajax请求的速度取决于用户计算机和浏览器之外的因素。 您不希望用户计算机挂起,因此请避免使用它。 而是尝试这样的事情。

  function a(passedData){ return $.ajax({ url : '/ajax.php', data : passedData }); } function b(passedData){ return $.ajax({ url : '/ajaxB.php', data : passedData }); } $.when(a(data),b(data)).then(function(successDataForA,successDataForB){ //Do code after all asynchronous ajax calls are done. //As a whole this is still asynchronous so other things can still run },function(failA,failB){ //This fail callback is not necessary but here it is if needed }); 

用这个

  $(document).ready(function () { $('#ajaxloading').hide() // hide it initially .ajaxStart(function () { $(this).show(); }) .ajaxStop(function () { $(this).hide(); }); }); 

这里“ajaxloading”是你要显示或隐藏的DIV的ID。 你可以把任何内容放在这个div中

如果您的加载图像是gif图像,那么很难在IE和Chrome中显示它,因为这些浏览器会在同步调用时停止对DOM组件的任何更改,并且一旦执行代码,它就会显示所有更改。 您可以在加载图像后立即放置警告框来测试它。

 $('#loading').dialog(); alert('loading image'); 

一旦提示它弹出,您现在可以看到在IE和chrome中加载图像作为警报停止线程执行,直到用户给出响应。

阅读此链接: [https://stackoverflow.com/questions/11946828/loading-gif-image-is-not-showing-in-ie-and-chrome]

我在过去让Aj在Ajax调用期间显示“loading …”消息时遇到了问题,即使是异步调用(这是我肯定建议您使用的),其中相同的代码在FF中有效。

使用IE工作的解决方法(在FF中没有任何损害)是做这样的事情:

 $('#loading').dialog(); setTimeout(function() { $.ajax(...); },1); 

也就是说,显示“加载”消息然后通过使用setTimeout()推迟Ajax调用 – 这使浏览器在当前JS完成之后但在超时开始之前重新绘制页面。

但是当然如果你正在进行同步请求,你可能会想要在$.ajax()方法之后使用其结果运行其他代码,所以你需要将所有这些代码移到你传递给setTimeout()的函数中setTimeout() (或者从那里调用它,无论如何)。