首页 > 解决方案 > 尝试从 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有关吗?

标签: javascriptphparraysjsonwordpress

解决方案


在 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>

推荐阅读