通过 fetch 将查询字符串参数发送到 php 无效

Sending query string parameters to php via fetch not working

我只是想通过获取 api 将查询字符串参数发送到(同一页面)php 脚本。目的是让我可以将 javascript 中存在的变量存储在 php $_SESSION 变量中。但是没用。

背景:我写了一些 javascript 来检测打开了几个单选按钮中的哪个。此单选按钮的值存储了我想作为 SSI 从数据库加载的 PHP 模板的名称。

所以我真的不想操纵 javascript 中的响应,我只想能够传递变量(在此示例中进行了硬编码,但打算来自 javascript变量)到 PHP $_GET 或 $_POST。

感谢到目前为止回答的人。

代码如下:

<?php 

if(isset ($_REQUEST['name'])){
    echo "The name param is received!";
}
else {
    echo "The name param is NOT received!";
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>
<body>

   <script>
 
       fetch('index.php?name=matt');

   </script>
</body>
</html> 

我建议你看看MDN Fetch() API documentation。您的 fetch() 缺少它的 headers、它的方法、响应分辨率(第一个 .then())和结果分辨率(第二个 .then())。

但是,您可能不想使用 fetch()。将 return 的页面结果获取到 JavaScript,而不是用户。您使用它的方式,看起来您只是希望用户直接转到该页面(在这种情况下,只是 <a href='?name=matt'>Click Me</a>)。

最后,我想你需要明白fetch()的目的是向JS环境发送数据,而不是为用户重新加载页面。无论如何,这是你的电话如果有效的话会是什么样子...

<script>
       fetch('index.php?name=matt', {
        'headers': {
            'Accept': 'text/html',
            'Content-Type': 'text/html'
        },
        'method':'GET',
        'body':'',
    })
   .then((response) => response.text())
   .then((responseText)=>{
       console.info("Response?");
       console.info(responseText);     // result: "The name param is received!...(and the rest of your page)
   });
</script>

如果你想把fetch() return $_GET and/or $_POST 变量传给可用的JS时尚,那就欢迎JSON和json_encode()走进你的心

制作一个新的 PHP 脚本,userdata.php,并按原样编码...

<?php
    header('Content-Type: application/json');   // send JSON header, let page know it's JSON
    print(json_encode(['name':$_POST['name']]));    // get the name
?>

有了这个,将上面的 JS 更新为...

fetch('http://www.example.com/your/script.php', {
    'headers': {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
    },
    'method':'POST',
    'body':JSON.stringify({'name':'matt'}),
})
.then((response) => response.json())
.then((responseJson)=>{
    console.info("Response?");
    console.info(responseJson);
});

请注意我在上面所做的更改:我使用 POST 方法,这为您提供了一种更简洁的发送数据的方式(即使用 body,而不是将其附加到 URL,如 '?...')。您的回复也是 .json(),而不是 .text()d。