我正在嘗試通過 JavaScript 中的 POST AJAX 呼叫為我正在創建的聊天系統發布表單資料,為什么以下內容不起作用?我試圖獲取一些檔案,但找不到。
<div id="view-chat-form">
<input id="message" type="text" name="chat_message" placeholder="write a message..."/>,
<input type="button" value="send" onclick="sendData()"/>
</div>
并使用以下 AJAX 代碼發送請求而不加載帶有散列字串的頁面以隱藏聊天 ID
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" cm);
}
</script>
和以下 php 代碼將訊息插入到訊息表中
<?php
include "session.php";
include "connection.php";
$id = "";
$hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
$sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 's', $hashed_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count > 0){
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
} else {
mysqli_free_result($result);
mysqli_close($connection);
header("Location: chat_error.php");
}
$msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
$username = $_SESSION["username"];
$date = date("d/m/Y");
$time = date("H:i:s");
$sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
mysqli_stmt_execute($stmt);
?>
uj5u.com熱心網友回復:
做這樣的事情
<script type="text/javascript">
function sendData(){
var id = <?php echo $hashed_id; ?>;
var msg = <?php echo $_POST['chat_message']; ?>;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(id,msg);
}
</script>
uj5u.com熱心網友回復:
不明白你為什么$_POST在 javascript中使用 php ,它不起作用。嘗試使用document.getElementById()抓取聊天訊息。
正確的方法如下圖。
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" cm);
}
</script>
同樣在您的 PHP 代碼中,為什么使用 json_decode()?該帖子不是 JSON 格式。也糾正一下。
更改以下代碼
$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;
到
$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/314712.html
標籤:javascript php 阿贾克斯
