簡體   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