簡體   English   中英

如何在分頁中使用Ajax獲取數據?

[英]how to get data using ajax in pagination?

我想使用ajax get方法從頁面中獲取3個數據。

javascript是

<script type="text/javascript">
  var busy = false;
  var limit = 15
  var offset = 0;
  var id = 150;

  function displayRecords(lim, off) {
    $.ajax({
      type: "GET",
      async: false,
      url: "s.php",
      data: "limit=" + lim + "&offset=" + off,
      cache: false,
      beforeSend: function() {
        $("#loader_message").html("").hide();
        $('#loader_image').show();
      },
      success: function(html) {
        $("#results").append(html);
        $('#loader_image').hide();
        if (html == "") {
          $("#loader_message").html('<button class="btn btn-default"    type="button">No more records.</button>').show()
        } else {
          $("#loader_message").html('<button class="btn btn-default"  type="button">Loading please wait...</button>').show();
        }
        window.busy = false;


      }
    });
  }

  $(document).ready(function() {
    // start to load the first set of data
    if (busy == false) {
      busy = true;
      // start to load the first set of data
      displayRecords(limit, offset);
    }

    $(window).scroll(function() {
      // make sure u give the container id of the data to be loaded in.
      if ($(window).scrollTop() + $(window).height() >  $("#results").height() && !busy) {
         busy = true;
        offset = limit + offset;
        // this is optional just to delay the loading of data
        setTimeout(function() { displayRecords(limit, offset); }, 500);
        // you can remove the above code and can use directly this function
        // displayRecords(limit, offset);
      }
    });

  });

 </script>

和s.php是

$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$id = $_GET['id'];
echo $id;

但是我無法獲取id的值,每次我嘗試以新方式出問題或顯示錯誤時,php文件都不會使用ajax獲取id值。 但是它將完美地獲得limit和offset的值。 限制和偏移量都不是常數,而id則是常數1。

我怎樣才能解決這個問題..?

您無法獲得$ id的值,因為它沒有在ajax請求中發送。

data: "limit=" + lim + "&offset=" + off + "&id=" + id,

您可能想在數據字符串中添加ID。 現在應該可以工作了。

試試看:

data: limit: lim, offset: off, id: id

您的id是一個變量,您需要將其作為以下參數之一傳遞給請求。

data: {
    'limit': lim,
    'offset': off,
    'id': id
}

避免手動編碼查詢字符串,因為jQuery自動為您執行以下操作:

data: "limit=" + lim + "&offset=" + off + "&id=" + id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM