我在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 = "";
}
}
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");
}
}
答案 0 :(得分:1)
您的sendMessage
功能不太正确 - 看看这个功能是否有帮助。
在原始函数中检查了receiveReq
的状态,该函数没有引用实例化的XMLHttpRequest对象sendReq
- 同样,即使使用了{{1},该请求也永远不会被发送因为sendReq
和open
调用位于检查响应的代码块中...
send
最初错过了param var声明,因此更正了。
<强>更新强>
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');
答案 1 :(得分:1)
这里我将展示如何发送/接收基本CRUD(创建,读取,删除,更新)应用程序的Ajax请求,您可以在代码中实现它。
首先是带有HTML输入元素的简单表单
<form action="controller.php" method="POST">
<input type="text" class="form-control" name="userName"/>
<input type="text" class="form-control" name="password"/>
<input type="Submit" value="Log In" onclick="logIn(); return false;"/>
</form>
之后我们编写使用formData对象的JavaScript函数,并使用AJax技术发送请求:
function logIn()
{
//Creating formData object
var formData = new FormData();
//Getting input elements by their classNames
var formElements = document.getElementsByClassName("form-control");
//Append form elements to formData object
for(var i = 0; i < formElements.length; i++)
formData.append(formElements[i].name, formElements[i].value)
//Creating XMLHttpRequest Object
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "controller.php");
xmlHttp.send(formData);
}