我正在用 AJAX 编写一个基本应用程序,需要通过 POST 将一些数据发送到 php 页面。
我遇到的问题是 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 = "";
}
}
聊天服务器.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");
}
}
最佳答案
您的 sendMessage
函数不太正确 - 看看它是否有帮助。
在原始函数中,该函数检查了 receiveReq
的状态,它没有引用实例化的 XMLHttpRequest 对象 sendReq
- 而且,请求永远不会被发送,即使它使用 sendReq
因为 open
和 send
调用在检查响应的代码块内...
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info(response);
}
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.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
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 */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
sendReq.open( "POST", 'chatServer.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
document.getElementById("message").value = "";
}
}
/* send some messages */
sendMessage('message=ciao');
sendMessage('message=ajax...sent via POST');
最初错过了 param var 声明所以更正了。
更新
chatserver.php (example)
------------------------
<?php
/*
demo_chatserver.php
*/
session_start();
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
include your db connection
set your headers
*/
if( isset( $_POST['message'] ) && !empty( $_POST['message'] ) ){
@ob_clean();
/* Create the db conn && test that it is OK */
/* for the purposes of the tests only */
$_POST['date']=date( DATE_COOKIE );
echo json_encode( $_POST, JSON_FORCE_OBJECT );
exit();
}
}
?>
html / php page
---------------
<!doctype html>
<html>
<head>
<title>ajax tests</title>
<script type='text/javascript'>
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info( 'This is the response from your PHP script: %s',response );
if( document.getElementById("message") ) document.getElementById("message").innerHTML=response;
}
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.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
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 */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
/*NOTE: I have this in a folder called `test`, hence the path below!! */
sendReq.open( "POST", '/test/demo_chatserver.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
if( document.getElementById("message") ) document.getElementById("message").innerHTML = "";
}
}
/* send some data - including original 'message=ciao' but other junk too */
window.onload=function(event){
sendMessage('message=ciao&id=23&banana=yellow&php=fun&method=post&evt='+event);
}
</script>
</head>
<body>
<output id='message' style='display:block;width:80%;float:none;margin:5rem auto;padding:1rem;box-sizing:content-box;border:1px solid black;'>
<!--
Expect to see content appear here....
-->
</output>
</body>
</html>
Should output something like:-
------------------------------
{"message":"ciao","id":"23","banana":"yellow","php":"fun","method":"post","evt":"[object Event]","time":1446730182,"date":"Thursday, 05-Nov-15 13:29:42 GMT"}
关于javascript - AJAX 未正确发送 POST 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33543107/