我正在使用香草JS通过AJAX向数据库发送请求。数据被毫无问题地写入数据库。在刷新页面之前,我看不到正在数据库中放置的内容。删除内容时也会发生同样的情况,必须刷新才能看到内容消失。
我已经阅读并观看了一些指导性说明,但似乎没有在代码中找到错误。我可以单击一个按钮并即时加载“临时”代码,但是当涉及到数据库时,我无法重新创建相同的功能。
JavaScript
function postMessage(name, message){
var author = document.getElementById(name).value;
var message = document.getElementById(message).value;
var xhr = ajaxObj("POST", location.href);
xhr.onreadystatechange = function(){
if(ajaxReturn(xhr) == 'posted'){
var currentHTML = document.getElementById('comments').innerHTML;
document.getElementById('comments').innerHTML = '<div id="post_'+id+'"><p>'+author+' : '+'</p><p>'+message+'</p><button id="message_'+id+'" onclick="deleteMessage('+id+')">Delete Message</button>' + data;
document.getElementById(message).value = '';
}
}
xhr.send("action=postMessage&author="+author+"&message="+message);
}
html / php
<form class="" action="index.html" method="post">
<input type="text" name="name" id="name" value="" placeholder="Name"><br/>
<textarea name="message" id="message" rows="8" cols="80"></textarea><br/>
<button type="button" name="button" onclick="postMessage('name', 'message')">Post Message</button>
</form>
<div id="comments">
<?php
if(isset($_POST['action']) && $_POST['action'] == 'postMessage'){
$author = $_POST['author'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (author, message) VALUES ('$author', '$message')";
$db_link->query($sql);
$db_link->close();
return "posted";
exit();
}
$all_posts = $db_link->query("SELECT * FROM comments");
while($post = $all_posts->fetch_assoc()){
$author = $post['author'];
$message = $post['message'];
$date = $post['entered'];
$post_id = $post['id'];
$new_post .= "<div id='post_'$post_id>
<p>$author : $date</p>
<p>$message</p>
<button id='message_$post_id' onclick='deleteMessage($post_id)'>Delete Message</button>";
}
echo $new_post;
?>
</div>
查询已在数据库上成功执行,但是直到手动刷新页面后,我才看到带有消息的新div。在PHP代码或JS控制台中没有记录任何错误。
答案 0 :(得分:0)
创建一个新文件以提交数据,如save.php
并使用xhr.onload
检查执行是否成功
function postMessage(name, message){
var author = document.getElementById(name).value;
var message = document.getElementById(message).value;
var xhr = ajaxObj("POST", 'save.php');
xhr.onload = function () {
var currentHTML = document.getElementById('comments').innerHTML;
document.getElementById('comments').innerHTML = '<div id="post_'+id+'"><p>'+author+' : '+'</p><p>'+message+'</p><button id="message_'+id+'" onclick="deleteMessage('+id+')">Delete Message</button>' + data;
document.getElementById(message).value = '';
};
xhr.send("save.php/action=postMessage&author="+author+"&message="+message);
}