下面脚本的目的是允许用户发布新的更新并删除它们而不刷新页面:这就是我使用AJAX的原因。
有两个故障:
当用户发布更新时,它正确保存在数据库中,正确的更新在我的表中向下滑动但是当我查看源代码时,我可以看到错误的postid被回显(它始终是从数据库中的几行开始。
当用户删除帖子时,前端没有任何反应:tr不会向上滑动但是该行在数据库中被正确删除。
PHP部分:
echo "<table id=\"update_list\">
<tr class=\"cell$postid\">
<td>$post
<div id=\"delete\">
<span class=\"delete_update\"><a href=\"#\" id=\"$postid;\">X</a></span>
</div>
<hr>
</td>
</tr>
</table>";
AJAX部分:
<script type="text/javascript">
$(function() {
$("#addpost_button").click(function()
{
var element = $(this);
var boxval = $("#status").val(); // #status is the ID of the input where the users type in updates
var dataString = 'post='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$.ajax({
type: "POST",
url: "update_post.php",
data: dataString,
cache: false,
success: function(html){
$("#cell").prepend(html);
$("#update_list tr:first").slideDown("slow");
document.getElementById('post').value='';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click",function()
{
var ID = $(this).attr("id");
var dataString = 'postid='+ ID;
if(confirm("Sure you want to delete this post? "))
{
$.ajax({
type: "POST",
url: "delete_post.php",
data: dataString,
cache: false,
success: function(html){
$(".cell"+ ID).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
非常感谢任何帮助!
编辑: 来自update_post.php的代码:
<?php
include "includes/config.php";
if(isset($_POST['post']))
$table=query("INSERT INTO postlist (id, postid, post) VALUES (?, ?, ?)",
$_SESSION["id"], '', $_POST["post"]);
$table = query("SELECT post, postid FROM postlist WHERE id = ? ORDER BY postid DESC",
$_SESSION["id"]);
foreach ($table as $row){
$post=$_POST['post'];
$postid = $row["postid"];
echo "<table id=\"update_list\">
<tr class=\"cell$postid\">
<td>$post
<div id=\"delete\">
<span class=\"delete_update\"><a href=\"#\" id=\"$postid;\">X</a></span>
</div>
<hr>
</td>
</tr>
</table>";
}
?>
答案 0 :(得分:1)
你必须替换
<span class=\"delete_update\"><a href=\"#\" id=\"$postid;\">X</a></span>
到
<span class=\"delete_update\"><a href=\"#\" id=\"$postid\">X</a></span>
答案 1 :(得分:0)
当您发布到堆栈溢出时,这可能只是一个简单的格式错误......但这部分应该是......
foreach ($table as $row){
$post= $row['post'];
$postid = $row["postid"];
...rest of code
}
...不
foreach ($table as $row);
$post= $_POST['post'];
$postid = $row["postid"];
{