0

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

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]
];

所以我想用 map_with_me.php 文件生成的动态位置填充 beachs3 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);
 })
4

2 回答 2

0

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

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

应该足够了。

于 2012-04-29T01:23:22.837 回答
0

你有没有尝试过:

var beaches3 =  JSON.parse(jqxhr.responseText);
于 2012-04-29T01:31:00.283 回答