[英]Change div's content after clicking on a link using Ajax request
我的div包含一個具有SQL查詢的PHP函數,該查詢從threads
表中獲取最新線程。 我頁面的結構是這樣的;
Section # 1 --- Link 1
Section # 2 --- Link 2
Section # 3 --- Link 3
我要做的是使它像單擊Link 1
時一樣顯示Section 1
中的最新線程,單擊Link 3
時則顯示Section 3
中的最新線程。
請注意:我知道我可以使用slidetoggle()jQuery函數顯示和隱藏div,但是我想這樣做,以便在單擊鏈接時可以運行sql查詢以顯示最新線程。 我正在使用以下jQuery;
jQuery(document).ready(function($)
{
$('a[id^="forum_name"]').on('click', function (e)
{
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type: "POST",
url: 'latest_threads.php?fid='+fid,
dataType: 'json',
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
});
});
});
我的PHP文件latest_threads.php
具有以下代碼;
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
$forum['forum_threads'] = kalachi_forum_threads($fid);
}
?>
我的HTML就像;
<a href="javascript:void(0);" id="forum_name" fid="{$forum['fid']}" title="See latest threads of this section.">{$forum['threads']}</a>
<div id="forum_threads_{$forum['fid']}" style="display: none;">{$forum['forum_threads']}</div>
但這不起作用,請幫忙!
據我所知,您沒有輸出您的答復。
嘗試這樣的事情:
...
$forum['forum_threads'] = kalachi_forum_threads($fid);
echo $forum['forum_threads']
exit();
...
我添加了回顯線,以將實際響應輸出回您的瀏覽器。
jQuery(document).ready(function($){
$('a[id^="forum_name"]').on('click', function (e){
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type : "post",
dataType: "html",
url : "misc.php?action=forum_threads&fid="+fid,
cache: false,
success : function(response)
{
$("#forum_threads_"+fid).stop().slideToggle("fast").html(response);
}
});
});
});
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
echo $forum['forum_threads'] = kalachi_forum_threads($fid);
exit;
}
?>
將最后一行更改為此:
<div id="forum_threads_{$forum['fid']}"></div>
您可以閱讀Ajax教程。
但是對於您而言,您應該知道代碼的這一部分在div
中顯示的data
:
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
是您的php代碼的響應。
您的php響應是您php代碼的任何輸出,它可以是簡單的echo 'something'
或html代碼,或者包括html文件等。
在您的php代碼中生成一個html代碼或包含一個html文件,您想要在div中顯示的任何內容。
注意:請始終在您的php代碼末尾放置die()
或exit()
。
這是一個簡單的例子:
HTML :
<div id="c1" onclick="javascript:loadcontent(1);">click</div><br>
<div id="c2" onclick="javascript:loadcontent(2);">click</div><br>
<div id="c1" onclick="javascript:loadcontent(3);">click</div><br/
Javascript(jquery) :
<script>
function loadcontent(id) {
$.post("yourphp.php", {id: id}, function(data) {
if (data) {
$("#c" + id).html(data);
}
else
{
alert("error");
}
});
}
</script>
PHP-yourphp.php :
<?php
$id = $_POST['id'];
require 'filename'.$id.".html";
die;
?>
然后,您必須創建3個html文件,其名稱為: filename1.html , filename2.html , filename3.html,然后將要顯示在ID為c1,c2或c3的div中的所有內容放入其中。
而已
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.