在javascript中显示json数据不起作用
我已经创建了一个var并向它传递了JSON数据(逗号分隔的值),但是当我想显示JSON数据时,它只返回null。代码如下:在javascript中显示json数据不起作用,javascript,json,Javascript,Json,我已经创建了一个var并向它传递了JSON数据(逗号分隔的值),但是当我想显示JSON数据时,它只返回null。代码如下: <script type="text/javascript"> var data1 = [ {order:"145",country:"Dubai",employee:"permanent",customer:"self"} ]; document.write(data1); </script> 变量数据1=[ {订单:“145”、
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
变量数据1=[
{订单:“145”、国家:“迪拜”、员工:“永久”、客户:“自我”}
];
文件写入(数据1);
您可以这样做:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
或者你可以这样做
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
无论哪种方式,在列表中只存储一个对象都会使这个答案有点多余,除非我向您展示如何在多个对象上循环
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
我在这里也使用了jQuery的混合,这可能不是最优的,但至少它表明有多种方法可以实现您所需要的
另外,数组上的forEach()方法是MDN开发的方法,因此它可能不兼容交叉浏览器,只是提醒一下
如果您想要纯JS,这是一种方法
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
为了简单快速地打印JSON,您可以执行如下操作,对象也可以执行类似操作
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
现在要在屏幕上打印,一个简单的for in循环就足够了,但请不要使用e,它不会打印数组,而是打印[object]。为了简单起见,我不会深入到屏幕中打印数组键和值
希望这对某人有用。干杯
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}
for(json中的变量i){
document.writeln(''+i+''+json[i]+'
');
log(i+''+json[i])
}
问题是什么?标题与你文章的内容有什么关系?@Eimantas我认为你在编辑时太随意了;当然不清楚海报是否是你写的意思。@lanzz可能是。我从这段代码推导出这个问题。