【问题标题】:ajax only works once then stops after clickajax 只工作一次然后在点击后停止
【发布时间】:2012-01-18 20:48:22
【问题描述】:

我正在尝试加载下一组数据,然后在 ajax 调用后删除数据。但我只让ajax工作一次。点击“获取更多报价”后,没有任何反应。

网站:http://kdevs.site40.net/#more(点击获取更多报价)

阿贾克斯:

 function getQuotes(start, limit) {
            //Clear the recent list element
            $(".recent-list").html("");
            $.ajax({

              url: "quotes.php?start=" + start + "&limit=" + limit,
              success: function (data) {
                ata = jQuery.parseJSON(data);
                console.log("success");
                //Data should now be a javascript array of objects.
                for (i = 0; i < data.length; i++) {
                  var newElem = jQuery("<li></li>").attr('id', data[i].id).addClass('quote-wrap-group');
                  newElem.append("<div class='quote'><p>" + data[i].quote + "</p></div>");
                  $(".recent-list").append(newElem);
                }
              }
            });
          }

               $("#more").click(function () {
                 var currentIndex = 0;  
                 getQuotes(currentIndex = currentIndex + 10, 10);
                 currentIndex += 10;
               });

PHP 返回 json:

<?php

    require("inc/connect.php");
    $start = $_GET['start'];
    $limit = $_GET['limit'];

    $sql = "SELECT * FROM entries ORDER BY id DESC LIMIT ".$start.", ".$limit;
    $result = mysql_query($sql, $link) or die("Error in query: ".mysql_error());

    $data = array(); 

    while($row = mysql_fetch_array($result)) {
        array_push($data, $row);
    }

    echo(json_encode($data));
?>

我知道这不是 PHP,因为:http://kdevs.site40.net/quotes.php?start=0&limit=10 有效。

我做错了什么?

【问题讨论】:

  • 您的查询受到 SQL 注入的影响。阅读en.wikipedia.org/wiki/SQL_injection,然后修复它。
  • ^ 我知道。如果我将它发送给客户,我会先解决这个问题......

标签: php javascript jquery ajax


【解决方案1】:

每次单击#more 按钮时,都会将 currentIndex 重置为 0,因此您基本上总是会加载前 10 个 cmets。
删除var currentIndex = 0; 并将其添加到点击事件函数之外

【讨论】:

  • 你先回答了,谢谢!我还能做些什么来修复/改进我的代码吗?
【解决方案2】:

粗略一瞥表明问题出在这里:

$("#more").click(function () {
    var currentIndex = 0;  
    getQuotes(currentIndex = currentIndex + 10, 10);
    currentIndex += 10;
});

每次点击#more你的当前索引都会重置为0;在点击处理程序之外声明currentIndex,不要重置它。

【讨论】:

  • 天哪,谢谢!很简单!我的代码中还有什么需要修复/更好的吗?
【解决方案3】:

currentIndex 初始化移出点击处理程序,您将添加两次,更改为:

var currentIndex = 0;
var count = 20;
$("#more").click(function () {
    getQuotes(currentIndex, count);
    currentIndex += count;
});

【讨论】:

  • 你永远不会得到引号 0 -> 10
猜你喜欢
  • 2022-01-14
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 2018-07-01
  • 2022-08-13
相关资源
最近更新 更多