我有一个脚本,它读取Json字符串的内容并创建一个表来显示数据。只要我在JQuery函数中包含Json字符串,这就可以正常工作。我需要做的是调用另一个返回Json字符串的php文件。
我编写了返回Json字符串的脚本:
[{"ClientName":"Name","RoomName":"Room 2","RoomFromTime":"06:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 6","RoomFromTime":"06:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 1","RoomFromTime":"07:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 14","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 12","RoomFromTime":"07:00:00","RoomToTime":"19:00:00"},{"ClientName":"Name","RoomName":"Room 10","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 9","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 8","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 7","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 5","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 3","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 4","RoomFromTime":"08:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 15","RoomFromTime":"08:00:00","RoomToTime":"19:00:00"}]
我的JQuery函数具有以下内容:
$(document).ready(function () {
var json = $.getJSON("get_data.php", function(data){
var tr ;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + json[i].ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + json[i].RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + json[i].RoomFromTime + " - " + json[i].RoomToTime + "</div></td>");
$('table').append(tr);
}
});
});
使用对其他php脚本的调用不会在表中显示返回的数据。现在我知道我在某个地方出了问题,但是任何人都可以看到我做错了什么。
非常感谢你的时间。
答案 0 :(得分:1)
因为默认情况下getJSON是异步工作的,所以在回调运行时不会填充json变量。将回调更改为:
$.getJSON("get_data.php", function(json){
...
看来你的实际杰森周围有一个包装。 要么像这样解决它:
$.getJSON("get_data.php", function(json){
json = json[0].data;
...
或将其修复为get_data.php。
答案 1 :(得分:0)
您可以使用此100%正常工作代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("get_data.php", function(data){
$.each(data, function(i, field){
var tr ;
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + field.ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + field.RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + field.RoomFromTime + " - " + field.RoomToTime + "</div></td>");
$('table').append(tr);
});
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>