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

查看:10
本文介绍了同时针对同一事件的两个 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 url 目标分配给随机字符串(比如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");
      }           
    }); 
  });
});

请参考以下Fiddle.

推荐答案

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天全站免登陆