简体   繁体   中英

Why doesn't my PHP code echo out $_POST data?

The XHR Request shown here is sending an array to process.php. The array just contains strings ex.['hello', 'name'].

var xmlHTTP;
if (window.XMLHttpRequest)
{
    xmlHTTP = new XMLHttpRequest();
}
else
{
    xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHTTP.onreadystatechange = function ()
{
    if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200)
    {
          alert(this.responseText);
    }
}
var queryString = "";
for(var i = 0; i < all_data.length; i++)
{
    queryString += "data"+i.toString()+"=" + all_data[i];
    if(i < all_data.length - 1)
    {
           queryString += "&";
    }
}
xmlHTTP.open("POST", "www.example.com/process.php", true);
xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHTTP.send(queryString);

The PHP code below is just designed to echo out the POST data. As just a test, I wanted to see what the value of data0 would be, but when I go to www.example.com/process.php, I get an error Notice: Undefined index: data0 in /var/www/html/process.php on line 2 . However, when I navigate back to the page where the javascript is, it alerts the response with the correct data that was sent. Why doesn't the data be shown in the PHP file?

<?php
        echo $_POST["data0"];
?>

I ran your code in my environment and it worked exactly as expected.

I created the index.html file with the javascript code involved by the <script> tag and i created the process.php file with your php code.

I set all_data to ["hello", "name"]

Thus, when opening index.html in browser , the XHR call is made to process.php and "hello" ( data0 ) is returned accordingly.

Perhaps your mistake is in trying to access process.php directly (without po), instead of executing the javascript code. The javascript should be make the call to PHP.

I hope I helped you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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