我正在編寫一個基本的AJAX應用程序,需要通過POST發送一些數據到一個php頁面。AJAX不能正確發送POST變量
我在這裏得到的問題是,PHP頁面沒有正確接收$ _POST中的數據:如果我嘗試打印其內容,我得到一個空數組。
你能幫我指出問題嗎?
// global variables
var sendReq = getXmlHttpRequestObject();
// get the browser dependent XMLHttpRequest object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else {
document.getElementById('status').innerHTML =
'Status: Error while creating XmlHttpRequest Object.';
}
}
// send a new message to the server
function sendMessage() {
if (receiveReq.readyState == 0 || receiveReq.readyState == 4) {
sendReq.open("POST", 'chatServer.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// bind function call when state change
sendReq.onreadystatechange = messageSent;
var param = "message=ciao";
sendReq.send(param);
// reset the content of input
document.getElementById("message").value = "";
}
}
chatServer.php
<?php session_start();
// send headers to prevent caching
header("Expires: Mon, 1 Jul 2000 08:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
// open database
$file_db = new PDO('sqlite:chatdb.sqlite') or die("cannot open database");
if ($file_db) {
print_r($_POST); // this prints an empty array!!!
// check if a message was sent to the server
if (isset($_POST["message"]) && $_POST["message"] != '') {
$message = $_POST["message"];
// do stuff
}
}
?>
編輯:
更新功能,仍然沒有工作
function sendMessage() {
if(sendReq){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if(sendReq.readyState==4) {
if(sendReq.status==200){
/* Process response here */
clearInterval(timer);
getUnreadMessages();
}
}
};
/* Open & send request, outwith the listener */
sendReq.open("POST", 'chatServer.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var param = 'message=ciao';
sendReq.send(param);
document.getElementById("message").value = "";
// relocate to php page for debugging purposes
window.location.replace("chatServer.php");
}
}
通過使用'window.location的.replace'你發送請求,但不要等待答案 - 相反,你加載php腳本 - 這是行不通的。使用控制檯查看ajax請求中發生了什麼。 – RamRaider
謝謝,那正是發生了什麼事。 POST正在工作,但我正在以錯誤的方式進行測試。 – Ivano