gpt4 book ai didi

javascript - 更多在同一页面调用ajax以显示更多数据

转载 作者:行者123 更新时间:2023-12-01 01:57:52 26 4
gpt4 key购买 nike

我有一个显示一些帖子的页面:当我单击“其他文章”时,我会计算主 div 中的文章数量,并在 php 脚本中通过 ajax 调用传递此变量。

//JS (ajax)
$(document).ready(function() {
$(".otherArticle").click(function() {
var numPosts = $("#posts > div").length; // get number of post in the page
$.ajax({
type: "GET",
url: "script.php",
data: {
'number': numPosts
},
dataType: "html",
success: function(data) {

$("#posts").html(data) // write in #posts the new data
},
error: function() {
alert("Noob");
}
});
});
});

我的 HTML

<div id="posts">
<div class="article">...</div>
<div class="article">...</div>
<div class="article">...</div>
<button class="otherArticle"></button>
</div>

开头有3篇文章。当我单击“otherArticle”时,我会在 php 脚本中传递文章数量,其中我在文章数量上添加 5。之后,我执行查询以选择限制为 5+3 的其他文章

/*script.php*/
<?php
//include connect db
$numberNewPosts= $_GET['number'] + 5 ;
$query= "select posts from myTab limit 0, ". $numberNewPosts ." ";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
echo "<div= 'article'> ". $row['posts '] ." </div> ";
}
echo "<button class='otherArticle'></button>";
?>

点击一次即可,显示8篇文章(5+3)。但是第二次点击的时候就不行了。我希望它有 8 篇文章,并在我的 php 脚本中添加其他 5 篇文章。有任何想法吗?

最佳答案

刚刚注意到@ADyson 已经回答了这个问题。解决方案:

这是因为你的按钮位于“posts”div 内。像这样更改您的代码:

HTML

<div id="posts">
<div class="article">...</div>
<div class="article">...</div>
<div class="article">...</div>
</div>
<button class="otherArticle"></button>

PHP

//include connect db
$numberNewPosts= $_GET['number'] + 5 ;
$query= "select posts from myTab limit 0, ". $numberNewPosts ." ";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)){
echo "<div class='article'> ". $row['posts '] ." </div> ";
}

关于javascript - 更多在同一页面调用ajax以显示更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50874185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com