如何从json获取值并在javascript中显示它们 [英] How can i get values from json and display them in javascript

查看:75
本文介绍了如何从json获取值并在javascript中显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网页上获取json。页面上的json格式为

I want to get json from a web page. The json on the page is in the format

[{"ID":"151032",
  "user":"UsersName",
  "message":"This is a message.",
  "date":"1293452007",
  "replies":"1",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"}] 

如何获得用户消息 ID 从JSON回复并通过javascript在另一个网页上显示?

How can I get user, message, ID and replies from the JSON and display it on another webpage via javascript?

示例:hello UsersName您的Id是:151032,您的消息是:这是一条消息。它有1个回复。

Example: hello UsersName your Id is: 151032 and your message is: This is a message. it has 1 replies.

注意:这将有多套,即

[{"ID":"151032",
  "user":"UsersName1",
  "message":"This is a message.",
  "date":"1293452007",
  "replies":"1",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"},
 {"ID":"151033",
  "user":"UsersName2",
  "message":"This is another message.",
  "date":"1293452007",
  "replies":"2",
  "categories":false,
  "categoriesArray":[],
  "lat":"0.000000000000000",
  "lng":"0.000000000000000"}]


推荐答案

使用 JSON.parse 然后访问属性,如普通对象属性。例如,

Use JSON.parse and then access the properties like normal object properties. E.g.

var msgs = JSON.parse(json);

for(var i = 0, l = msgs.length; i < l; i++) {
    var msg = msgs[i];
    var div = document.createElement('div');
    div.innerHTML = 'Hello ' + msg.user + ' your Id is: ' + msg.ID + 'and your message is: ' + msg.message + ' it has ' + msg.replies + ' replies';
    document.body.appendChild(div);
}

工作 DEMO

这篇关于如何从json获取值并在javascript中显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆