使用jQuery和AJAX从数据库中显示更多结果
I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:
<a href="javascript:ShowPost();">Show Posts</a>
<div id="result"></div>
jQuery Part:
function ShowPost(){
$.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
function(data) {
$("#result").html(data);
});
};
PHP Part:
if ($_POST['action'] == "showpost") {
$db->query( "SELECT title FROM post LIMIT 0,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}
Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...
i hope you understand my question.
我正在尝试在模板中使用AJAX创建新闻块。 所以我在HTML部分写了一个简单的代码: p>
&lt; a href =“javascript:ShowPost();”&gt; Show Posts&lt; / a&gt;
&lt; div id =“result”&gt;&lt; / div&gt;
code> pre>
jQuery Part: p>
function ShowPost() {
$ .post(dir +'engine / ajax / posts.php',{action:“showpost”},
function(data){
$(“#result”)。html(data); \ n});
};
code> pre>
PHP部分: p>
if($ _POST ['action' ] ==“showpost”){
$ db-&gt; query(“SELECT title FROM post LIMIT 0,5”);
while($ row = $ db-&gt; get_row()){
echo $ row ['title']。“&lt; br&gt;”;
}
}
code> pre>
问题是,如何在首次点击后获得更多结果? 例如,在第一次 strong>点击显示帖子 strong>链接后,我可以显示来自数据库的5条新闻。 在第二次 strong>点击显示帖子链接后,我需要显示6到10个新闻,在第三个 strong>中点击从11到15获取结果并继续...... p>
我希望你理解我的问题。 p>
div>
Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:
jQuery Part:
var pageNumber = 0;
function ShowPost() {
pageNumber++;
$.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
function(data) {
$("#result").html(data);
});
};
Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.
PHP Part:
if ($_POST['action'] == "showpost") {
var pageSize = 5;
var pageNumber = $_POST['pageNumber'];
var from = (pageNumber - 1) * pageSize;
var to = pageNumber * pageSize;
$db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);
while ( $row = $db->get_row()) { echo $row['title']."<br>"; }
}
Take a hidden field in html and update it's value after every success call and when next time you call for next record send that value in post.
<input type="hidden" name="limit" value="5">
<a href="javascript:ShowPost();">Show Posts</a>
<div id="result"></div>
Just implement the pagination limit in ur query
var offset = -5;
function ShowPost(){
offset = offset + 5;
$.post(dir + 'engine/ajax/posts.php', {action:"showpost",offset:offset},
function(data) {
$("#result").html(data);
});
};
PHP part
if ($_POST['action'] == "showpost") {
$vOffset = $_POST['offset'];
$db->query( "SELECT title FROM post LIMIT $vOffset,5 " );
while ( $row = $db->get_row() ) {
echo $row['title']."<br>";
}
}