AJAX POST and PHP

…衆ロ難τιáo~ 提交于 2020-01-03 05:53: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.

The AJAX script is

xmlhttp.open("POST","handle_data.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain");
var cmdStr="cmd1=Commanda&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?


回答1:


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/




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/3289294/ajax-post-and-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!