开发者

AJAX POST and PHP

开发者 https://www.devze.com 2023-01-08 14:08 出处:网络
I have a AJAX script which sends a POST request to PHP with some values. When I try to retrieve the values in PHP, am not able to get anything.

I have a AJAX script which sends a POST request to PHP with some values. When I try to retrieve the values in PHP, am not able to get anything.

The AJAX script is

xmlhttp.open("POST","handle_data.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain");
var cmdStr="cmd1=Commanda&am开发者_如何学JAVAp;cmd2=Command2";
xmlhttp.send(cmdStr);
alert(xmlhttp.responseText); 

The PHP script is

<?php
  echo $_POST['cmd1'];
?>

The output is just a plain empty alert box. Is there any mistake in the code?


xmlhttp.onreadystatechange = function()
{
    if(this.readyState == 4 && this.status == 200)
    {
        if(this.responseText != null)
        {
            alert(this.responseText);
        }
    };
}

You need to wait for the data to be received, use the onreadystatechange to delegate a callback.

http://www.w3.org/TR/XMLHttpRequest/


I don't know if it is required, but might you want to use application/x-www-form-urlencoded as the request header.


You should not be grabbing the response immediately after sending the request. The reason is because the A in Ajax stands for Asynchronous, and that means the browser won't wait for your XMLHttpRequest to complete before it continues to execute your JavaScript code.

Instead you should write a callback that only runs when the response is fully ready. Just before your xmlhttp.send(cmdStr); call, add this:

xmlhttp.onreadystatechange = function()
{
    if (this.readyState == 4 && this.status == 200)
    {
        // This line is from your example's alert output
        alert(this.responseText);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消