javascript - 尝试从 php 脚本中检索回显数据时,getJSON 不起作用
问题描述
我还花了几个小时通过阅读 stackoverflow.com 上的类似帖子来弄清楚如何解决这个问题,但我不知道该怎么做。
因此,对于您的信息,我使用 Wordpress 作为 CMS。
我有一个 php 脚本(getlocations.php),它返回一个二维数组的编码 JSON 对象:
// getlocations.php
<?php
$returnarray = array();
$returnarray[0] = array();
$returnarray[0]['name'] = "Peter";
$returnarray[0]['city'] = "NYC";
$returnarray[1]['name'] = "Dave";
$returnarray[1]['city'] = "NYC";
echo json_encode($returnarray);
?>
现在我想使用我网站上的数据并使用 javascript 进行进一步处理。所以我拿了一个 Wordpress-Codeblock 并将这段代码放入:
<script type='text/javascript'>
jQuery(document).ready(function($){
console.log("Test");
$.getJSON('getlocations.php', function(data) {
console.log(data);
console.log("Test2");
// do something with the data
});
});
</script>
控制台打印出“测试”,但仅此而已。它可能与wordpress有关吗?
解决方案
在 Wordpress 中使用文件的完整 URL 路径。例如,如果 getlocations.php 在模板中,请使用 get_template_directory_uri 函数。
<script type='text/javascript'>
jQuery(document).ready(function($){
console.log("Test");
$.getJSON('<?php echo get_template_directory_uri(); ?>/getlocations.php', function(data) {
console.log(data);
console.log("Test2");
// do something with the data
});
});
</script>
推荐阅读
- android-studio - 将 Android Studio 更新到版本 3.4.2
- javascript - 计数器没有根据功能改变颜色
- javascript - 使用 ES6 样式导入的 mocha 测试
- nginx - 为什么 Nginx 将我的子域重定向到域根目录?
- google-apps-script - 如何在谷歌脚本中构建这种类型的 UI?
- android - 有什么方法可以知道用户的 InApp 和订阅购买是否已经在全新的应用安装时恢复?
- reactjs - 使用 jest 测试 formik onSubmit 函数不起作用
- c# - 如何使用 topshelf 将 asp.net core 2.1 MVC 应用程序部署为 Windows 服务
- c++ - Cgo 找不到像这样的标准库
- java - 如何获得两个 jsonArrays 之间的差异?