[英]Loading PHP Response with Jquery Ajax POST
我有一個php腳本,可以遍歷數據庫查詢的結果並將其打印出來。 我正在嘗試使用AJAX將它們加載到管理界面面板中,但無濟於事。 我的工作要求我主要編寫后端代碼,因此我還沒有去學習很多JS / Jquery。 無論如何,我有一個頁面“ insert.php”,該頁面上有一個我想單擊的按鈕,並讓它調用“ posts.php”頁面中的結果。 這是我的檔案
<a href="#" class="button expand" id="ajaxbtn">Load Posts</a>
</div>
</div>
<div class="row main">
<div class="small-8 columns" id="posts">
</div>
</div>
</div>
<?php
require_once 'connect.php';
$user = 'admin';
$sql = "SELECT * FROM posts WHERE author = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $user);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$id = $row['id'];
$title = $row['title'];
$author = $row['author'];
$date = $row['date'];
$smalltext = $row['smalltext'];
$bodytext = $row['bodytext'];
$images = $row['images'];
$imagelist = split(' ', $images);
$shorttext = str_replace(
array("\r\n", "\n"),
array("</p><p>", "</p><p>"),
$smalltext);
echo
"
<div class='row main'>
<h1 class='padding-top-12 bottom-rule-green'>$title</h1>
<div class='small-2 columns'>
<p class='text-justify small-text'>
Post MetaData goes here
</p>
</div>
<div class='small-10 columns bottom-rule-red text-justify'>
<p>
$shorttext
";
foreach ($imagelist as $key => $value)
{
echo "<img src='users/$author/img/$value'>";
}
echo
"
</p>
</div>
</div>
<div class='row main small-text padding-top-1'>
<div class='small-2 small-oofset-2 columns'>
<a href='posts/$author/$id'>Edit Post</a>
</div>
<div class='small-4 columns'>
Timestamp: $date
</div>
<div class='small-4 columns'>
Author: <a href='users/$user'>$user</a>
</div>
</div>
";
}
?>
$.ajaxSetup ({
cache: false
});
var loadUrl = "../../includes/posts.php";
$(function(){
$('#ajaxbtn').on('click', function(e){
e.preventDefault();
$('#ajaxbtn').fadeOut(300);
$.post(loadUrl, {language: "php", version: 5},
function(res){
$("posts").html(res)
}, "html");
});
});
<!--Foundation Framework Necessities-->
<script type="text/javascript" src="../../assets/js/vendor/jquery.js"></script>
<script type="text/javascript" src="../../assets/js/foundation/foundation.min.js"></script>
<script type="text/javascript" src="../../assets/js/postAjax.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
當我單擊#ajaxbtn按鈕時,它會淡出,因此我知道JS正在對該元素onclick調用JS,但是它不會發布posts.php的結果。 我認為這可能只是我對Ajax的工作方式的誤解; 請告訴我我做錯了什么。
嘗試改變,
$("posts").html(res)
至
$("#posts").html(res)
另外,我在posts.php中的代碼中看到一些錯誤,您沒有將php變量正確地嵌入字符串中。
我相信您需要使用委托事件。 從以下位置更改代碼:
$('#ajaxbtn')。on('click',function(e)
至:
$('#ajaxbtn')。on('click','a',function(e)
這樣,即使該父元素的內容發生更改,事件處理程序也會按預期觸發。 我有同樣的問題,這解決了它。 祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.