【问题标题】:PHP to Javascript ArrayPHP 到 Javascript 数组
【发布时间】:2015-02-04 14:13:00
【问题描述】:

我正在尝试使用 PHP 创建一个 Javascript 数组。当我运行 PHP 代码(如下)时,它会返回必要的数组。

      $counties = 'SELECT * FROM house_price_data_db.county_median_months where county=$1 or county=$2 or county=$3 order by county';
      $result_counties = pg_query_params($dbconn,$counties,array($county1,$county2,$county3)) or die('Query failed: ' . pg_last_error());
      $county_meds_php = array();
      while($r = pg_fetch_assoc($result_counties)) {
          $county_meds_php[] = $r;
      }
      echo("county_med_month=".json_encode(array_values($county_meds_php), JSON_NUMERIC_CHECK).";");

      pg_close($dbconn);?>

这是我在 Javascript 中调用信息的地方的片段:

county_1="Dublin";
county_2="Galway";
county_meds(county_1,county_2);
function county_meds(a,b){
  if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   xmlhttp.open("GET","county_med_month.php?c_1="+a+"&c_2="+b,false);
   xmlhttp.send()
}

然后当我尝试调用时:

if(county_med_month.length > 0)
    console.log("The array was created!, the problem was with my JavaScript code!");

我收到此错误:

ReferenceError: county_med_month is not defined

建议/建议?

【问题讨论】:

  • 在您的 ajax 代码中没有任何地方实际捕获脚本的响应,所以正如错误所说,country_med_month 永远不会被定义。
  • 在客户端,数据以文本形式接收,要么在AJAX请求中指定响应数据类型,要么手动解析
  • 将 PHP 执行后的最终 javascript 代码粘贴到另一个代码框中(使用您的浏览器内置的 Inspector 工具)

标签: javascript php arrays referenceerror


【解决方案1】:

可能会遗漏一些东西,但是:

1) 您的 php 响应必须是有效的 JSON 字符串

echo("county_med_month="

这不会让 JSON 之神高兴。

2) 你的 php 应该发送一个标头

header( "Content-type: application/json" );

我相信您想太多了,请在 PHP 中尝试一下。

$stuff = ''; // work on stuff later...
$return = array(); // declare variables
$return['county_med_month'] = $stuff // stuff is your content

header( "Content-type: application/json" );
die( json_encode( $return ) );

在 Javascript 中使用 jQuery 安全地抽象 ajax 调用。

$.get( 'php_url.php' , function( response ){

    console.log( response.county_med_month ); // contains you 'stuff'

});

【讨论】:

  • 您能否进一步了解如何将我上面的内容转换为 AJAX 以完成我需要做的事情,只是我不太了解?
【解决方案2】:

我认为您正在尝试通过执行county_med_month=x 从 php 设置 javascript 变量。那是不可能的。

在您的 PHP 代码中,只需以 json 格式返回数组:

  $counties = 'SELECT * FROM house_price_data_db.county_median_months where county=$1 or county=$2 or county=$3 order by county';
  $result_counties = pg_query_params($dbconn,$counties,array($county1,$county2,$county3)) or die('Query failed: ' . pg_last_error());
  $county_meds_php = array();
  while($r = pg_fetch_assoc($result_counties)) {
      $county_meds_php[] = $r;
  }

  header( "Content-type: application/json" ); // set the header to json
  echo(json_encode($county_meds_php, JSON_NUMERIC_CHECK)); // this will return json

  pg_close($dbconn);?>

与javascript相比,当http请求处于就绪状态时,您应该将内容解析为json数组:

county_1="Dublin";
county_2="Galway";

var county_med_month = [];

county_meds(county_1,county_2);

function county_meds(a,b){

    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // this method is used to capture the response of the http request
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            county_med_month = JSON.parse(xmlhttp.responseText);

            // and now you can use the array
            if(county_med_month.length > 0)
                console.log("The array was created!, the problem was with my JavaScript code!");
        }
    }

    xmlhttp.open("GET","county_med_month.php?c_1="+a+"&c_2="+b,false);
    xmlhttp.send()
}

为了更容易实现,我建议使用jQuery$.get方法。

【讨论】:

  • 我已尝试实施建议的解决方案,但收到以下错误:codeSyntaxError: JSON.parse: JSON 数据后出现意外的非空白字符code
  • 尝试将echo(json_encode(array_values($county_meds_php), JSON_NUMERIC_CHECK));改成echo(json_encode($county_meds_php, JSON_NUMERIC_CHECK));
  • 好的,已经解决了,唯一的问题是当我尝试在county_meds() 函数ReferenceError: county_med_month is not defined 之外使用数组时,我得到了这个。有没有办法让它在函数之外访问?
  • 是的,您可以在函数外声明变量,而不仅仅是在函数内设置。我更新了答案。
猜你喜欢
  • 1970-01-01
  • 2011-01-09
  • 2014-03-30
  • 1970-01-01
  • 2013-03-07
  • 2013-04-06
  • 2015-10-06
  • 2013-09-18
  • 2011-01-17
相关资源
最近更新 更多