我有一个 php 脚本,它循环数据库查询的结果并将其打印出来。我正在尝试使用 AJAX 将它们加载到管理界面面板中,但无济于事。我的工作要求我主要编写后端代码,所以我没有时间学习太多 JS/Jquery。无论如何,我有一个页面“insert.php”,其中有一个我想单击的按钮,并让它调用“posts.php”页面的结果。这是我的文件
插入.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>
posts.php
<?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>
";
}
?>
postAjax.js
$.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,但它不会发布 posts.php 的结果。我认为这可能只是我对 Ajax 工作原理的误解;如果您愿意,请告诉我我做错了什么。
最佳答案
尝试改变,
$("posts").html(res)
到
$("#posts").html(res)
此外,我在 posts.php 中的代码中发现了一些错误 您没有正确地将 php 变量嵌入到字符串中。
关于javascript - 使用 Jquery Ajax POST 加载 PHP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615819/