我有一个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正在调用该元素,但它没有发布posts.php的结果。我想这可能只是我对Ajax工作方式的误解;如果你愿意,请告诉我我做错了什么。
答案 0 :(得分:1)
尝试更改,
$("posts").html(res)
到
$("#posts").html(res)
此外,我在posts.php中看到了代码中的一些错误 您没有正确地将php变量嵌入到字符串中。
答案 1 :(得分:0)
我相信您需要使用委托活动。更改您的代码:
$('#ajaxbtn')。on('click',function(e)
为:
$('#ajaxbtn')。on('click','a',function(e)
这样,即使父元素的内容发生更改,事件处理程序也会按预期触发。我有同样的问题,这解决了它。祝你好运。