简体   繁体   English

AJAX未正确发送POST变量

[英]AJAX is not correctly sending POST variables

I'm writing a basic application in AJAX that need to send some data over POST to a php page. 我正在用AJAX编写一个基本应用程序,该应用程序需要通过POST将一些数据发送到php页面。

The problem I'm getting here is that the php page is not correctly receiving data in the $_POST: if I try to print its content I get an empty array. 我在这里遇到的问题是php页面无法正确接收$ _POST中的数据:如果我尝试打印其内容,则会得到一个空数组。

Can you help me point out the problem? 您能帮我指出问题吗?

// 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 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
    }
}


?>

EDIT: 编辑:

Updated function, still not working 更新功能,仍然无法正常工作

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");
    }
}

Your sendMessage function is not quite right - have a look at this to see if it helps. 您的sendMessage函数不太正确-查看此函数是否有帮助。

In the original the function checked for the status of receiveReq which does not refer to the instantiated XMLHttpRequest Object sendReq - also, the request would never get sent even if it had used sendReq because the open and send call was within the code block that checked the response... 在原有的功能的状态检查receiveReq这并不是指实例化XMLHttpRequest对象sendReq -还,请求就永远也不会,即使它曾使用发送sendReq因为opensend呼叫是检查的代码块中响应...

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');

Originally missed the param var declaration so corrected that. 最初错过了param var声明,因此更正了该声明。

update 更新

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"}

Here I will show how I send/receive Ajax requests for basic CRUD (Create, Read, Delete, Update) applications and you can implement it in your code. 在这里,我将展示如何发送/接收基本CRUD(创建,读取,删除,更新)应用程序的Ajax请求,您可以在代码中实现它。

First of all simple form with input elements in HTML 首先是带有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>

After that we write JavaScript function that uses formData object and with AJax technique sends request: 之后,我们编写使用formData对象并使用AJax技术发送请求的JavaScript函数:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM