简体   繁体   English

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

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

I'm currently struggling to figure out how to pass variables from JS to PHP using Ajax. 我目前正在努力弄清楚如何使用Ajax将变量从JS传递到PHP。 I have tried using the following Ajax code 我尝试使用以下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;
        }

    }
}

Combined with a PHP script called welcome.php which looks as follows: 结合了一个名为welcome.php的PHP脚本,该脚本如下所示:

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

For some reason, however, this outputs 'NULL' and I can't work out why. 但是由于某种原因,此输出为“ NULL”,我无法弄清原因。

I've also tried including echo $user; 我也尝试过包含echo $user; in file welcome.php, but this doesn't return anything. 在文件welcome.php中,但这不会返回任何内容。

Anyone know why this is happening? 有人知道为什么会这样吗?

you are using method GET, as stated in .send documentation 您正在使用GET方法,如.send文档中所述

If the request method is GET or HEAD, the argument is ignored and request body is set to null. 如果请求方法是GET或HEAD,则忽略参数,并将请求主体设置为null。

What you want to do is 你想做的是

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