【问题标题】:How to access data from php file using fetch api method?如何使用 fetch api 方法从 php 文件中访问数据?
【发布时间】:2020-05-18 11:32:27
【问题描述】:

我想在控制台打印从 api 获取的数据
我的 php 文件代码是
<?php echo "Hello"; ?>

我的 javascript 文件代码是

function cities(str){
    alert(str);
    let url = "cities.php";
    fetch(url).then( (response)=>{return response; }).then((data)=>{console.log(data);});
}

我正在使用 HTML 文件中的 onclick 属性调用此函数,我想在我的控制台上看到 Hello,但它给我的输出为 like this,当我更改我的 javascript 文件代码时,如

function cities(str){
    alert(str);
    let url = "cities.php";
    fetch(url).then( (response)=>{return response.text(); }).then((data)=>{console.log(data);});
}

然后在控制台中将输出作为php文件see here的完整代码

【问题讨论】:

  • 我的回答对你有帮助吗?

标签: javascript php fetch fetch-api


【解决方案1】:

您的第二个代码 sn-p(带有 response.text())在 JavaScript 方面是正确的。

您现在得到了整个 PHP 文件,因为您的网络服务器不执行文件并返回评估结果,而是将其视为普通文件。

您现在需要做什么取决于网络服务器(例如apache2nginx)和您希望执行 PHP 的方式(例如CGIfpm)。你可以找Configure &lt;your webserver&gt; for PHP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2019-12-09
    • 2019-07-13
    • 2023-04-02
    • 2015-07-09
    相关资源
    最近更新 更多