两个ajax同时请求同一事件。什么应该是典型的行为?如果请求是同步的,它是如何不同的 [英] Two ajax requests on same event at same time . what should be the typical behaviour? how it is different if request is synchronous

查看:98
本文介绍了两个ajax同时请求同一事件。什么应该是典型的行为?如果请求是同步的,它是如何不同的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的javascript代码中,我同时发送两个Ajax请求。

使用Firebug进行分析后,我得出了一个不寻常的结论:

哪个(Ajax)响应首先打印最后打印

In the following javascript code, I am sending two Ajax request at the same time.
After analysis using Firebug, I came to unusual conclusion that :
"which ever (Ajax) response is coming first is printing last".

问题2:如果我分配Ajax网址目的地到一个随机字符串(比如abcd)[不存在]那么ajax调用的总数将增加到3?

Problem 2: if I assign the Ajax url destination to a random string (say "abcd") [which don't exist] then total number of ajax call will be increased to 3?

$(document).ready(function(e) {

  $("form[ajax=true]").submit(function(e) {

    e.preventDefault();

    var form_data = $(this).serialize();
    var form_url = $(this).attr("action");
    var form_method = $(this).attr("method").toUpperCase();

    $("#loadingimg").show();

    $.ajax({
      url: form_url, 
      type: form_method,      
      data: form_data,     
      cache: false,
      success: function(returnhtml){                          
        alert ("a");
        // $("#result").html(returnhtml); 
        // $("#loadingimg").hide();                    
      }           
    });   

    $.ajax({
      url: form_url, 
      type: form_method,      
      data: form_data,     
      cache: false,
      success: function(returnhtml){                          
        // $("#duplicate").html(returnhtml); 
        // $("#loadingimg").hide();
        alert("b");
      }           
    }); 
  });
});

请参阅以下小提琴

推荐答案

Gaurav,你有一个错误,在第一个$ .ajax的结尾必须以)结束,,第二个为

Gaurav, you have an error, at the end of the 1st $.ajax it must end as ), and 2nd as ).

您不能以结尾;

var result1;
var result2;
$.when(
    $.ajax({ // First Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){     
                result1 = returnhtml;                  
        }           
    }),

    $.ajax({ //Seconds Request
        url: form_url, 
        type: form_method,      
        data: form_data,     
        cache: false,
        success: function(returnhtml){                          
            result2 = returnhtml;     
        }           
    })

).then(function() {
    $('#result1').html(result1);
    $('#result2').html(result2);
});

这篇关于两个ajax同时请求同一事件。什么应该是典型的行为?如果请求是同步的,它是如何不同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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