0

我正在尝试使用 get 从按钮获取信息,然后吐出一个数组。到目前为止,在运行此代码时,.getJSON没有调用 (当我取出查询时,它可以工作,但我找不到查询有任何问题)。

以下是相关代码:

Javascript:

$.getJSON("/westcoast_map.php", // The server URL
{
    westcoast_id: $('.opener').data('westcoast_id')
}, // Data you want to pass to the server.
function (json) {

    var id = json[0];
    waypts = json[1];
    alert(id);
    console.log(waypts);

});

php 脚本(westcoast_map.php):

<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
include_once("config.php");

$westcoast_id    = $_GET['westcoast_id'];
$westcoast_array = array();
$query           = "SELECT city, state FROM users GROUP BY city";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {

    if ($row['city'] != '' && $row['state'] != '') {
        $westcoast_array[$row] = "{location:" . $row['city'] . ", " . $row['state'] . ", stopover:true}";
    }
}
$data = array(
    $westcoast_id,
    $westcoast_array
);
echo json_encode($data);
?>

按钮

<button type="button" class="opener" data-westcoast_id="westcoast_id" onclick="calcRoute();">
    West Coast
</button>
4

2 回答 2

1

在我看来你错过了key你的valuefor 状态,试试这个:

if($row['city'] != '' && $row['state'] != '') {
    $westcoast_array[] = "{
        location:".$row['city'].", 
        state:".$row['state'].", 
        stopover:true
    }";
}

您还使用数组作为键,这是您无法做到的。更改$westcoast_array[$row]$westcoast_array[]

于 2013-03-01T21:43:07.407 回答
0

如果我错了,我很抱歉,但我认为你正在JSON自己制作并使用json_encode它再次编码。尝试这个:

<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
include_once("config.php");

$westcoast_id    = $_GET['westcoast_id'];
$westcoast_array = array();
$query           = "SELECT city, state FROM users GROUP BY city";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {

    if ($row['city'] != '' && $row['state'] != '') {
        $westcoast_array[] = array("location" => $row['city'], "state" => $row['state'], "stopover" => true);
    }
}
$data = array(
    $westcoast_id,
    $westcoast_array
);
echo json_encode($data);
?>
于 2013-03-08T15:01:32.577 回答