如何在另一个php文件中从ajax获取变量


How get variable from ajax in another php file

问题是,当我点击"提交数据"按钮时,我会得到响应(这是正确的),但当我单击"转到php文件"链接(与以前的php文件相同)时,我就会得到Undefined index:firstname和Undefined index:lastname错误。我该怎么修?

这是我的代码:

<html>
<head>
    <script>
        function ajax_post(){
            // Create our XMLHttpRequest object
            var hr = new XMLHttpRequest();
            // Create some variables we need to send to our PHP file
            var url = "my_parse_file.php";
            var fn = document.getElementById("first_name").value;
            var ln = document.getElementById("last_name").value;
            var vars = "firstname="+fn+"&lastname="+ln;
            hr.open("POST", url, true);
            // Set content type header information for sending url encoded variables in the request
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // Access the onreadystatechange event for the XMLHttpRequest object
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var return_data = hr.responseText;
                    document.getElementById("status").innerHTML = return_data;
                }
            }
            // Send the data to PHP now... and wait for response to update the status div
            hr.send(vars); // Actually execute the request
            document.getElementById("status").innerHTML = "processing...";
        }
    </script>
</head>
<body>
    <h2>Ajax Post to PHP and Get Return Data</h2>
    First Name: <input id="first_name" name="first_name" type="text">  <br><br>
    Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
    <input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
    <div id="status"></div>
    <a href="my_parse_file.php">go to the php file</a>
</body>

和php文件

<?php 
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

因为两者都是不同的请求:

当您使用AJAX传递参数firstnamelastname时。您必须使用GET请求在URL中传递相同的内容。

转到php文件

<?php 
echo 'Thank you '. $_REQUEST['firstname'] . ' ' . $_REQUEST['lastname'] . ', says the PHP file';
?>

输出:

感谢abc xyz,PHP文件说

它将在Submit buttonHyperlink中工作。

通过单击链接,浏览器不会向服务器端发送POST请求,而是发送GET请求。这就是为什么全局数组$_POST不包含您试图在PHP文件中检索的元素。错误消息指出$_POST数组中没有像"firstname"answers"lastname"这样的元素。建议添加检查数组元素是否存在,如下所示:

<?php
    if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
        echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
    } else {
        echo 'Nothing to say';
    }

感谢R J的解释。现在我把它修好了,工作正常。

但我很担心,因为我使用这个代码只是为了训练。在我的主要问题中,我需要通过ajax将真实对象(而不是字符串等)发送到我的php站点,所以我无法将其添加到url中,可以吗?