我有一个显示一些帖子的页面:当我点击“其他文章”时,我计算主 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 已经回答了这个问题。解决方案:
这是因为您的按钮位于“帖子”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> ";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句