Seb*_*ian 1 php jquery json get
打印时,数组值返回为"undefined",即使使用print_r($items)我可以看到数组不为空.这可能是什么问题?
MySQL的:
名为'nights'的表格,名为'name','price','day','queue jump','closing'和'doors'.他们都是人口稠密的.
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);
?>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
你的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"
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |