Ajax与jQuery同步.是否有可能? [英] Ajax synchronous with jQuery. Is it possible?

查看:65
本文介绍了Ajax与jQuery同步.是否有可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I put a sleep(5) in ajax.php page. I need the code returned to start another function group. It is also using ajax. My first ajax call looks like this:

$.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正在使用它.

Why I cannot show to the loading message in IE and Chrome? Just Firefox is working with that.

推荐答案

异步代码最好.同步代码可能会挂起您的浏览器,这对于ajax来说是个坏主意,因为ajax请求的速度取决于用户计算机和浏览器之外的因素.您不希望用户计算机挂起,因此请避免挂起.而是尝试这样的事情.

Asynchronous code is best. Synchronous code can hang your browser, which makes it a bad idea in the case of ajax, where the speed of the ajax request depends on factors beyond the users computer and the browser. You don't want the users machine to hang, so avoid it. Instead try something like this.

 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
 });

这篇关于Ajax与jQuery同步.是否有可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆