从 php 文件中获取 api(获取数据)

fetch api (GET DATA) from php file

我正在尝试从 php 文件中获取值

api.php

      <?php
      // want to fetch this value 
      $a = 'come!! fetch this value';

      ?>

我的 javascript 页面有这样的代码。(此代码不在页面 api.php 上)

            fetch('http://localhost/react_task/react-webpack-boilerplate/php/api.php', {
        method: 'get',
        // may be some code of fetching comes here
    }).then(function(response) {
            if (response.status >= 200 && response.status < 300) {
                return response.text()
            }
            throw new Error(response.statusText)
        })
        .then(function(response) {
            console.log(response);
        })

能否指导我如何使用 fetch 从 php 文件中获取变量值。

您没有回显该值,因此不会发送。

<?php
// want to fetch this value 
$a = 'come!! fetch this value';
echo $a;
?>

你的php需要输出你想要的值。一个简单的方法是使用 echo。例如:

echo 'come!! fetch this value';

您应该使用 echo 在 php 中显示它,然后它会在您的 JavaScript 响应中可用。