如何合并这些ajax调用

时间:2012-06-20 02:25:56

标签: javascript jquery ajax

我上了一堂课,但是我认为它是低效的,因为我可以在1次时将DOM浸入DOM中3次。我不认为你需要看到剩下的代码,所以我只发布效率低下的部分以保持整洁:

function showSelectedAttr(){

    var productID = <?php echo $product_info['products_id'];?>;
    var sizeID = 0; 
    var tallID = 0;
    var colID = 0;

    $(".sizeopt").each(function() {
          if ($(this).is(':checked'))  sizeID = $(this).val();                         
     });

     $(".tallopt").each(function() {
          if ($(this).is(':checked'))  tallID = $(this).val();                         
     });

     $(".mine_color").each(function() {
          if ($(this).is(':checked'))  colID = $(this).val();                          
     });

    $.ajax({
              type: "POST",
              url: 'get_product_attribute.php',
              data: "product_id="+ productID +"&size_id="+ sizeID,
              success: function( response ) {       
                    $("#attr_container").html(response);
              } 
     });

     $.ajax({
              type: "POST",
              url: 'get_product_attribute.php',
              data: "product_id="+ productID +"&size_id="+ tallID,
              success: function( response ) {       
                    $("#attr_container_tall").html(response);
              } 
     });

         $.ajax({
              type: "POST",
              url: 'get_product_attribute.php',
              data: "product_id="+ productID +"&size_id="+ colID,
              success: function( response ) {       
                    $("#attr_container_color").html(response);
              } 
     });

}

正如你所看到的,ajax api被称为3个单独的时间。有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

function showSelectedAttr() {

    var productID = <?php echo $product_info['products_id'] ?>;
    var sizeID = 0; 
    var tallID = 0;
    var colID = 0;

    $(".sizeopt").each(function() {
        if ($(this).is(':checked')) sizeID = $(this).val();                         
    });

    $(".tallopt").each(function() {
         if ($(this).is(':checked')) tallID = $(this).val();                         
    });

    $(".mine_color").each(function() {
         if ($(this).is(':checked')) colID = $(this).val();                          
    });

    $.ajax({ 
        dataType:"json",
        type: "POST", 
        url: 'get_product_attribute.php', 
        data: {
            productId : productID,
            sizeId : sizeID,
            tailId : tailID,
            colId : colID
        }, 
        success: function( response ) {    
            $("#attr_container").html(response.Text);
            $("#attr_container_tall").html(response.Tall);
            $("#attr_container_color").html(response.Color);
        }  
    }); 
}

响应是json格式为{Text: "value", Tall: "value", Color: "value" }