繁体   English   中英

为什么这个Ajax请求似乎没有将JS变量传递给PHP?

[英]Why does this Ajax request not seem to pass the JS variable through to PHP?

我目前正在努力弄清楚如何使用Ajax将变量从JS传递到PHP。 我尝试使用以下Ajax代码

xhr = new XMLHttpRequest();

function myFunction() {
    xhr.open("GET", "welcome.php");
    xhr.send("your_name=john&your_age=40");

    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            document.getElementById("output").innerHTML = xhr.responseText;
        }

    }
}

结合了一个名为welcome.php的PHP脚本,该脚本如下所示:

$user = $_GET['your_name'];
var_dump($user);

但是由于某种原因,此输出为“ NULL”,我无法弄清原因。

我也尝试过包含echo $user; 在文件welcome.php中,但这不会返回任何内容。

有人知道为什么会这样吗?

您正在使用GET方法,如.send文档中所述

如果请求方法是GET或HEAD,则忽略参数,并将请求主体设置为null。

你想做的是

xhr.open("GET", "welcome.php?your_name=john&your_age=40");

暂无
暂无

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

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