在HTML中显示我的JSON

时间:2015-12-28 20:05:26

标签: javascript html json

这些是我的Json数组:

{"0":"1","id":"1","1":"2015-01-11 12:30:45","DateTimeCreated":"2015-01-11 12:30:45","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"benjiwjh","username":"benjiwjh"}

{"0":"4","id":"4","1":"2015-02-11 09:09:09","DateTimeCreated":"2015-02-11 09:09:09","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"LSH","username":"LSH"}

{"0":"7","id":"7","1":"2015-12-03 18:30:00","DateTimeCreated":"2015-12-03 18:30:00","2":"Unresolved","status_desc":"Unresolved","3":"SWJH","username":"SWJH"}

{"0":"12","id":"12","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"benjiwjh","username":"benjiwjh"}

{"0":"14","id":"14","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"CYJM","username":"CYJM"}

我应该如何使用它们在HTML文件中显示我的代码?

我有一个显示数据的功能,但它不起作用:

function showData(response) {

        var data = JSON.parse(response);

        var id = data.id;
        var DateTimeCreated = data.DateTimeCreated;
        var status_desc = data.status_desc;
        var username = data.username;


        myText.textContent= id + DateTimeCreated + status_desc + username;
}

3 个答案:

答案 0 :(得分:0)

我认为您的html模板中应该有 div 标记。

例如,在HTML模板中,应该有一个代码范围:

<div id="sometext">
</div>

在你的JS脚本中,

var textContent = id + DateTimeCreated + status_desc + username
sometext = document.getElementById("sometext");
sometext.innerHTML(textContent);

有关详细信息,请访问http://www.w3schools.com/js/js_output.asp

希望它会有所帮助

答案 1 :(得分:0)

基于这个问题,我不完全确定你何时使用showData函数。但是,这里有一个jsfiddle,表明它有效:https://jsfiddle.net/qyy2nvtz/1/

<p id='hello'></p>
var myText = document.getElementById('hello');

您需要先获取一个元素才能在其中显示内容。所以,我用一个id为'hello'的段落元素初始化了'myText'。

此外,在解析之前,请确保传递给showData的响应是一个字符串。如果它已经是一个对象,那么就不会对它进行解析。

答案 2 :(得分:0)

这里有一个例子,你需要一个div元素来引用像“js”:

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
  <div id="js">
  </div>
</body>
<script type="text/javascript">
    var myText= document.getElementById("js");
    var data = JSON.parse(response);
    var id = data.id;
    var DateTimeCreated = data.DateTimeCreated;
    var status_desc = data.status_desc;
    var username = data.username;
    myText.textContent = id + DateTimeCreated + status_desc +username;
</script>
</html>

进一步阅读:http://www.w3schools.com/dom/prop_element_textcontent.asp