打印时,数组值返回为'undefined',即使使用print_r($items)
我也可以看到数组不为空。这可能是什么问题?
MySQL的:
表格称为'之夜',列名为'名称','价格','日','排队跳','关闭'和'门'。他们都是人口稠密的。
eventinfo.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>
答案 0 :(得分:5)
您的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"
});