使用 $.get() 从 PHP 导入数组时出现问题


Issues importing array from PHP with $.get()

数组值在打印时返回为"未定义",即使通过使用print_r($items)我可以看到数组不为空。这里可能有什么问题?

MySQL:

名为"夜晚"的

表,其中的列称为"名称"、"价格"、"白天"、"排队跳跃"、"关闭"和"门"。它们都已填充。

活动信息.php:

<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
include('functions.php');
connect();
$night = $_POST['club'];
// this echos fine
$night = mysql_real_escape_string($night);
$query = "SELECT * FROM nights WHERE name = '$night'";
    $result = mysql_query($query);
    $items = array();
    if($result && mysql_num_rows($result) > 0) { 
        while ($row = mysql_fetch_array($result)) { 
        $items[] = array("price"=>$row['price'], "day"=>$row['day'], "queue jump"=>$row['queue jump'], "closing"=>$row['closing'], "doors"=>$row['doors']);
        }
    } 
    mysql_close(); 
    // convert into JSON format and print
    echo json_encode($items);
?>

.JS:

<script type="text/javascript">
    $(document).ready(function() {
// for simplicity's sake, but ultimately I'd like to load all the information
            $('#right_inside').html('<h2>' + $('#club').val() + '</h2>');
    });
    $('#club').change(function(event) {
        $.ajax({
            type: "post",
            url: "eventinfo.php",
            data:  $(this).serialize(),
            success: function(data) {
                $('#right_inside').html('<h2>' + $('#club').val() + '</h2><p>Day: ' + data.day + '</p>');
                },
            dataType: "json"
        });
    });
</script>

你的 JSON 结构是错误的。数据实际上是一个数组:

尝试将data.day更改为data[0].day

注意:你应该在 ajax 成功中使用 JSON.stringify(data) 来查看 JSON 的结构。

$.ajax({
  type: "post",
  url: "eventinfo.php",
  data:  $(this).serialize(),
  success: function(data) {
     alert(JSON.stringify(data));
     //or
     console.log(JSON.stringify(data));
  },
   dataType: "json"
 });