我创建了一个这种格式的外部 php 文件的 json:
[
{
"title": "Welcome!",
"description": "The world has changed dramatically..",
"image": "img/strawberry-wallpaper.jpg"
}
]
我正在使用它来将数据显示到特定的 div 部分,但我没有结果:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'json.php',
type: 'post',
data: { get_param: 'value' },
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj.success){
$.each(obj, function (index, item) {
if ('success'!= index){
$('#output').append("<div class='col-md-6' ><img class='img-rounded' src="+item.image+"alt='MyImage' width='550px' height='240px'></div><div class='col-md-6'><h3>"+item.title+"</h3><p class='well'>"+item.description+"</p><div class='row top-buffer'><div class='col-md-5 col-md-offset-1'><img src='img/link_icon.png' class='img-rounded' width='20px' height='20px'/><a href='www.link.com'>liNK</a></div><div class='col-md-6'><button class='btn btn-primary pull-right' id='btn'>Read More</button></a> </div></div></div>")
});
}
};
});
});
有人能注意到这段代码有什么问题吗?json格式是否正确?
最佳答案
data
已经是jQuery转换的对象。您不需要解析。
$(function() {
$.ajax({
url: 'json.php',
type: 'POST',
data: {get_param: 'value'},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data) {
// check with console
console.log(data);
$.each(data, function(index, item) {
$('#output').append("<div class='col-md-6' ><img class='img-rounded' src="+item.image+"alt='MyImage' width='550px' height='240px'></div><div class='col-md-6'><h3>"+item.title+"</h3><p class='well'>"+item.description+"</p><div class='row top-buffer'><div class='col-md-5 col-md-offset-1'><img src='img/link_icon.png' class='img-rounded' width='20px' height='20px'/><a href='www.link.com'>liNK</a></div><div class='col-md-6'><button class='btn btn-primary pull-right' id='btn'>Read More</button></a> </div></div></div>");
});
}
});
});
关于javascript - 使用 Ajax 和 jQuery 无法在 div 部分显示 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38011548/