javascript - file_get_contents PHP Uncaught SyntaxError:无效或意外令牌
问题描述
当我尝试让我们 file_get_contents 了解我的天气时,它向我显示了这个错误
我做错了什么 ??
我不能这样做:
<?php
function getWeather_PHP($location) {
$l_location = (string)$location;
$url = "http://api.openweathermap.org/data/2.5/weather?".$l_location."&lang=en&units=metric&appid=MY_API_KEY";
$url = (string)$url;
$contents = file_get_contents($url); //error occur here
...
return weather_data;
?>
在同一个 php 文件中的脚本中
<script>
var inputString = "PLACE_LOCATION"
var php_result = "<?php
$php_inputString = '"+inputString+"';
echo getWeather_PHP($php_inputString);
?>";
</script>
错误是: 在此处输入图像描述
我得到的另一个错误报告是
警告:file_get_contents("+this_url+"): failed to open stream: No such file or directory in /opt/lampp/htdocs/Index.php on line 50
解决方案
var php_result = "<?php
$php_inputString = '"+inputString+"';
echo getWeather_PHP($php_inputString);
?>";
PHP 在服务器上进行评估,早在 Javascript 运行之前。PHP 解释器<?php … ?>
直接输出标签之外的所有内容,而不以任何方式对其进行解释。
从 PHP 的角度来看,$php_inputstring
是设置为文字文本"+inputString+"
。这导致getWeather_PHP()
尝试获取 city 的天气"+inputString+"
,但失败了。
如果您需要getWeather_PHP()
可从 Javascript 调用该函数,则需要将其公开为单独的 AJAX 端点。无法以您在此处尝试的方式使 Javascript 和 PHP 互通。
推荐阅读
- r - 使用每行特定变量操作数据框的行
- django - Django 表单 - 如何在框内添加标签?
- python - 无法使用 Flask 登录用户
- netlify-cms - 在 Netlify CMS 中维护图像预览
- batch-file - 无法将批处理脚本的参数正确传递到循环语句内的命令中
- c++ - 在 NS3 中构建 Aquasim 模块的问题
- javascript - 如何在javascript(或jquery实现)中使用箭头键遍历contenteditable组件?
- python-3.x - 使用 YahooDailyReader 检索 AMZN 股票数据
- vuejs2 - VueJS:子 - 父组件更新
- javascript - 在 Razor 的 JavaScript 函数中编写 c# 代码