[英]AJAX call only works once with $(document).on('click')
[英]ajax only works once then stops after click
我正在尝试加载下一组数据,然后在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可以工作。
我究竟做错了什么?
每次您单击按钮#more时,都会将currentIndex重置为0,因此基本上总是加载前10条注释。
删除var currentIndex = 0;
并将其添加到click event函数之外
粗略浏览一下就可以发现问题出在这里:
$("#more").click(function () {
var currentIndex = 0;
getQuotes(currentIndex = currentIndex + 10, 10);
currentIndex += 10;
});
每次单击#more
您的当前索引将重置为0; 在点击处理程序之外声明currentIndex
,不要重置它。
将currentIndex
初始化移出单击处理程序,您要添加两次,请更改为:
var currentIndex = 0;
var count = 20;
$("#more").click(function () {
getQuotes(currentIndex, count);
currentIndex += count;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.