从 JSON 读取数据并显示在 html

Reading data from JSON and display in html

我想从外部 JSON 文件读取和显示数据并使用 HTML 显示它。

我目前拥有的:

Javascript:

var xmlhttpRoles = new XMLHttpRequest();
var urlRoles = "../portal/getResults.php";

xmlhttpRoles.onreadystatechange = function() {
    if (xmlhttpRoles.readyState == 4 && xmlhttpRoles.status == 200) {
        var rolesArray = JSON.parse(xmlhttpRoles.responseText);
        functionRoles(rolesArray);
    }
};
xmlhttpRoles.open("GET", urlRoles, true);
xmlhttpRoles.send();

function functionRoles(arr) {
    var out = "";
    var i;
    alert(arr);
    for(i = 0; i < arr.length; i++) {
        out += '<p>' + arr.results[i].Title +'</p>';
    }
    document.getElementById("id02").innerHTML = out;
}

getResults.php 文件输出:

{

"results": [
    {
        "DocId": 2204,
        "Title": "Lorem ipsum dolor sit amet, consectetur",
        "Locations": [
            {
                "State": "New York",
                "City": ""
            },
            {
                "State": "New York",
                "City": "New York City"
            }
        ],
        "Topics": [
            3,
            7,
            11
        ],
        "PublicationYear": "2011",
        "Organization": "New  Yorks Times",
        "WebLocation": "www.google.com",
        "Description": "Lorem Ipsum"
    }
],
"TotalMatches": 1

}

HTML:

<div id="id02"></div>

我一直在尝试获取 title 或任何其他元素的值,但没有成功。我不确定我做错了什么。

JSON 是一个对象,对象没有长度 属性。我认为您需要更改 for 条件:

for(i = 0; i < arr.results.length; i++) {
    out += '<p>' + arr.results[i].Title +'</p>';
}