通过Javascript加载大型HTML模板的最佳做法?

时间:2017-01-15 08:15:28

标签: javascript jquery html ajax

search.js

function search_function() {
     $("#search-button").attr('disabled','disabled');
     $("#product-container").empty();
     $(".paging_link").empty();
     $("#product-container").html('<div class="col-xs-12 text-center" style="margin-bottom: 25px; margin-top: 25px;"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span></div>');
     var num;
     $.ajax({
       type: 'POST',
       url: '/api/search.php',
       async: true,
       data: $('#search-capture').serialize() +"&page=1",
       success: function (data) {
         console.log(data);
         $("#product-container").empty();
         array = $.parseJSON(data)
         if(array[1].length > 0)
         {
           num = array[0];
           $.each(array[1], function (index, item) {
             $.ajax({
               type: 'POST',
               url: '/api/item.php',
               data: {item: item},
               async: false,
               success: function (data) {
                 if(data)
                 {
                     $("#product-container").append(data);
                 }
               }
             });
           });
           $("#search-button").removeAttr('disabled');
           history.pushState(null, null, "search.php?search="+$("#search").val()+"&sort="+$("#sort").val()+"&page=1");
         }
         else {
           num = 0;
           $("#search-button").removeAttr('disabled');
           $("#product-container").append('<div class="col-xs-12 text-center" style="margin-bottom: 25px;"><h1>No results for <i>"'+ $("input[name=search]").val() +'"</i>.</h1></div>');
         }
         $(".paging_link").bootpag({
            total: num,
            maxVisible: 5,
            page: 1
         });
      }
     });
   }

/api/item.php

<?php
  include_once("../library/config.php");
  include_once("../library/user.class.php");
  $user = new user($pdo);
  if(isset($_POST['item']))
  {
    $item = $_POST['item'];
    $image_array = json_decode($item['images']);
    $person = $user->person_exists($item['owner_id']);
  }

?>
<div class="col-md-3 col-md-offset-0 col-sm-4 col-sm-offset-0 col-xs-10 col-xs-offset-1" style="margin-bottom: 25px;">
  <div class="col-item">
          <div class="post-img-content">
              <img src="<?php echo $image_array[0]; ?>" style="height: 100%; width: 100%;"/>
              <span class="post-title">
                  <b><?php echo $item['name'];?></b><br>
              </span>
              <?php
              if($item['price'] > $item['sale_price'])
              {
              ?>
              <span class="round-tag">-<?php echo round(($item['price'] - $item['sale_price'])/$item['sale_price'] * 100); ?>%</span>

              <?php
              }
?>
          </div>
          <div class="info">
              <div class="row">
                  <div class="price col-md-12">
                      <h5>Offered By: <a href="/user.php?id=<?php echo $item['owner_id']; ?>"><?php echo $person['firstname']; ?> <?php echo $person['lastname']; ?></a></h5>

<?php
if($item['price'] > $item['sale_price'])
{
?>
<div><b>$<?php echo $item['sale_price']; ?></b> <s class="text-muted">$<?php echo $item['price']; ?></s> <br> + $<?php echo $item['shipping']; ?> Shipping</div>

<?php
}
else {
?>
<div><b>$<?php echo $item['price']; ?></b><br> + $<?php echo $item['shipping']; ?> Shipping</div>
<?php
}
?>
                  </div>
              </div>

              <div class="row">
                <div class="col-sm-10 col-sm-offset-1">
        <hr style="margin-top: 0px; margin-bottom: 10px;">
                </div>
                <div class="col-xs-6">
                  <form class="form" name="add-to-cart">

                  <div class="form-group form-group-sm" style="margin-bottom: 0;">
                    <input type="hidden" name="id" value="<?php echo $item['id'];?>">
                    <input type="hidden" name="quantity" id="quantity" placeholder="quantity" value="1">
                    <input type="hidden" name="action" value="addtocart">
                  <button class="btn btn-default btn-sm btn-block" type="submit" id="search-button"><i class="fa fa-shopping-cart"></i> </button>
                  </div>
                </form>
                </div>
                <div class="col-xs-6">
                  <div class="form-group form-group-sm" style="margin-bottom: 0; margin-top: 0px;">
                  <a href="details.php?id=<?php echo $item['id']; ?>" class="btn btn-default btn-sm btn-block"><i class="fa fa-list"></i></a>
                  </div>
                </div>
              </div>
          </div>
      </div>
</div>

这是我的Javascript函数来获取api调用的结果,我遇到的问题是加载时间,因为如果首先对/api/search.php进行AJAX调用以获取我想要显示的项目加上所有数据,如名称,价格,卖家ID等。然后它进行另一个AJAX调用/api/item.php我有一个HTML模板,我使用PHP并使用POST中的数据填充模板,并返回那个html并将其附加到文本中。但是,这使得加载非常缓慢,因为在第二次AJAX调用时,我必须将async设置为false以正确的顺序加载项目。我想知道在没有第二次AJAX调用的情况下加载项目项是否有更有效和可行的方法,而不是通过Javascript加载大量的HTML(我应该这样做吗?)。

1 个答案:

答案 0 :(得分:1)

您可以按顺序插入占位符元素,然后在ajax完成后可以用实际内容替换

所有跨度按顺序同步添加,因此您拥有最终数据的正确位置

$.each(array[1], function(index, item) {
    var loc = $("#product-container").append("<span/>").children().last();
    // loc is the span just appended
    $.ajax({
        type: 'POST',
        url: '/api/item.php',
        data: {
            item: item
        }
        success: function(data) {
            if (data) {
                loc.replaceWith(data); // replace the span with data
            } else {
                loc.remove(); // remove the no longer needed placeholder
            }
        }
    });
});

注意:我的jQuery很生疏,而我确实对方法做了简单的测试,我可能已经把jQuery塞进了某个地方

或者,如果您需要在启用搜索按钮和history-pushState之前等待所有这些ajax完成

$.when(array[1].map(function(item) {
    var loc = $("#product-container").append("<span/>").children.last();
    return $.ajax({
        type: 'POST',
        url: '/api/item.php',
        data: {
            item: item
        }
        success: function(data) {
            if (data) {
                loc.replaceWith(data);
            } else {
                loc.remove();
            }
        }
    });
})).then(function() {
    $("#search-button").removeAttr('disabled');
    history.pushState(null, null, "search.php?search=" + $("#search").val() + "&sort=" + $("#sort").val() + "&page=1");
});