我有一个新闻自动收报机,它可以很好地处理静态 html 数据,但我不知道如何在指定的 html 布局中显示动态数据。我无法将 json 数据解析到列表中。
提前致谢。
获取新闻.php
<?php
include 'connect.php';
$return = array();
$sql = "SELECT * FROM news";
$result = mysqli_query($db, $sql);
while($details = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$details_array['date'] = $details['date'];
$details_array['headline'] = $details['headline'];
$details_array['content'] = $details['content'];
array_push($return, $details_array);
}
echo json_encode($return);
?>
jQuery
<script type="text/javascript">
$(function(){
$.ajax({
type:'GET',
url: 'getnews.php',
success: function(data){
var response=JSON.parse(data);
$(function(){
$.each(response, function(i, item){
$('<ul>').append($('<li>').text(item.heading));
});
});
}
});
});
</script>
HTML 新闻代码
<div id="NewsTicker">
<ul>
<li><div>23rd<br>Sep</div><headline>Expandable Input</headline>
<p><news>Expandable Input is a minimal jQuery plugin to smoothly expand the width of a input filed when focused/clicked and collapse it when lose focus.</news></p>
</li>
<li><div>24th<br>Sep</div><headline>jQuery Photor Plugin</headline>
<p><news>Photor is a fast and easy jQuery plugin to create a responsive & touch-friendly full page image gallery with CSS3 transitions and transforms.</news></p>
</li>
<li><div>25th<br>Sep</div><headline>Metreaux Tables</headline>
<p><news>Metreaux Tables is a jQuery plugin to create nice, clean, themeable, andmodern Windows 8 UI Style data tables with the power of DataTables jQuery javascript library.</news></p>
</li>
</ul>
最佳答案
首先,如果您使用 AJAX 请求请求 JSON,您应该设置 dataType
到
"json"
这样您就不必手动解析它。即,
$.ajax({
type: 'GET',
url: 'getnews.php',
dataType: 'json',
success: function(data) {
...
}
});
从 jQuery 1.5 开始,您应该使用 .done()
从为的结果
$.ajax()而不是通过
success: ...
.即,
$.ajax({
type: 'GET',
url: 'getnews.php',
dataType: 'json',
}).done(function(data) {
...
});
你非常接近,但你想把你的 $.each()
直接打电话
在您的成功 回调中。使用 $(function() {...})
是捷径
对于 $(document).ready(function() {...})
注册的功能是
页面加载后调用。你应该这样做:
$.ajax({
type: 'GET',
url: 'getnews.php',
dataType: 'json'
}).done(function(data) {
$.each(data, function(i, item) {
...
});
});
现在,在你的 $.each()
里面回调,你正在创建一个新的 <ul>
, 和
添加一个 child <li>
到它,但实际上没有将它添加到页面。它
在我看来,您打算将每个项目附加到 <ul>
在下面
<div id="NewsTicker">
.为此,您需要执行以下操作:
var $newsList = $('#NewsTicker > ul');
$.each(data, function(i, item) {
$('<li>')
.append($('<div>').html(item.date))
.append($('<headline>').html(item.headline))
.append(
$('<p>').append(
$('<news>').html(item.content)
)
)
.appendTo($newsList);
});
关于jquery - 无法使用ajax将json数据解析为html列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592677/