使用httpRequest将php字符串传递给Javascript数组

时间:2012-04-29 01:18:19

标签: jquery json httprequest

我正在尝试使用httpRequest动态填充php请求中的javascript数组beaches3。

var jqxhr = $.get("http://127.0.0.1/websites/map_with_me.php?region="+region+"&suburb="+suburb+"&lat="+lat+"&lon="+lng, function() {
document.getElementById("thediv").innerHTML = (jqxhr.responseText);
var beaches3 = (jqxhr.responseText);
 })

map_with_me.php的输出是

 [
     ['Bondi Beach', -33.890542, 151.274856, 4],
     ['Coogee Beach', -33.423036, 151.259052, 5],
     ['Cronulla Beach', -34.028249, 121.157507, 3],
     ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
     ['Maroubra Beach', -33.450198, 151.259302, 1]
];

所以我想用beach_with_me.php文件生成的动态位置填充beaches3 var。

如果我用静态的海滩变量替换整个$ .get请求,那就可以了。

如何将php文件生成的动态javascript传递给javascript数组?

map_with_me.php

<?php 
echo "var beaches3 = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.423036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 121.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.450198, 151.259302, 1]
];"
?>

这有效:

var jqxhr = $.get("http://127.0.0.1/websites/map_with_me.php?region="+region+"&suburb="+suburb+"&lat="+lat+"&lon="+lng, function() {
document.getElementById("thediv").innerHTML = (jqxhr.responseText);
var beaches3 = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.423036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 121.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.450198, 151.259302, 1]
    ];
 })

这不是:

var jqxhr = $.get("http://127.0.0.1/websites/map_with_me.php?region="+region+"&suburb="+suburb+"&lat="+lat+"&lon="+lng, function() {
document.getElementById("thediv").innerHTML = (jqxhr.responseText);
var beaches3 = (jqxhr.responseText);
 })

2 个答案:

答案 0 :(得分:0)

如果您确定它是一个数组,而不是json或其他东西,只需执行:

$.get("/websites/map_with_me.php?region="+region+"&suburb="+suburb+"&lat="+lat+"&lon="+lng, function(data) {
    $("#thediv").html(data);
    var beaches3 = data;
});

应该足够了。

答案 1 :(得分:0)

你试过了吗?

var beaches3 =  JSON.parse(jqxhr.responseText);