【发布时间】:2017-06-22 11:55:51
【问题描述】:
我正在尝试进行某种简单的文字聊天。
我有两个 PHP 文件(index.php 和 send.php)和一个 javascript 脚本(script.js)。
在index.php,我得到了以下表格:
<form id="formSend" method="post">
<input id="inputMsg" class="form-control input-msg" type="text" name="msg" autocomplete="off">
<button id="btnSend" class="btn btn-success button-send" type="submit" name="send">Send</button>
</form>
为了防止页面重新加载,数据是通过我的 javascript 文件中的 ajax 请求发送的:
$('#formSend').submit(function(e){
e.preventDefault();
var url="send.php";
var posting = $.post(url, {msg: $('#input-msg').val() });
posting.done(function(data){
$('#inputMsg').val('');
console.log('success');
});
});
ajax 请求有效(成功记录在控制台中),但在send.php
什么都没有发生。
我在send.php 中使用以下代码:
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['msg']) && !empty(trim($_POST['msg']))){
$msg = htmlspecialchars(trim($_POST["msg"]));
$check = true;
}
else{
$check = false;
}
if ($check = true) {
$query = "INSERT INTO chat(message) values (?)";
$stmt = $mysqli->prepare($query);
if($stmt===false){
$error = 'Database error';
}
if(!$stmt->bind_param('s', $msg)){
$error = 'Database error';
}
if(!$stmt->execute()){
$error = 'Database error' . $mysqli->error;
}
if(empty($error)){
$mysqli->close();
$success = 'Success';
}
}
}
我错过了什么吗?我真的不知道为什么它不起作用...
【问题讨论】:
-
也许您应该输出 $error/$success 变量的内容,看看实际发生了什么……?
-
不用加
if ($_SERVER["REQUEST_METHOD"] == "POST")试试吧 -
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 请求使用的是 POST 方法 }
-
if($check = true)应为if($check)或if($check == true) -
当您对该脚本发出的请求是 AJAX 请求时,在这里使用 iframe 有什么意义……?这到底是什么意思——你是不是把
<iframe src="send.php"></iframe>放到你的页面上?那么当然你的 if 条件不会为真,因为浏览器会发出一个很好的旧 GET 请求来加载要在 iframe 中显示的文档。