读取JSON并插入HTML表

时间:2018-11-07 14:00:56

标签: javascript html json ajax request

在下面的代码中,我尝试在HTML表中显示源的字符串。这里的问题是,我看到的是字符串“ undefined”,而不是字符串。预先感谢!

    <!DOCTYPE html>
<html>
<body>

<h2>Table:</h2>

<p id="demo"></p>

<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "customers", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
            txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>"        
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "https://www.bayern-fahrplan.de/DDIP01?CoordSystem=WGS84&MinX=11%2C012742519378662&MinY=49%2C465725517007506&MaxX=11%2C035208702087402&MaxY=49%2C47637864525285&ts=154159795103", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

我测试了您的代码,并查看了响应中返回的JSON。返回对象的示例如下:

    {"CurrentStop":"KURGAR:1",
    "DayOfOperation":"07.11.2018",
    "Delay":227,
    "DirectionText":"Stadtgrenze",
    "ID":"35094510",
    "JourneyIdentifier":"2009441",
    "Latitude":"49,466061",
    "LatitudeBefore":"49,467044",
    "LineText":"38",
    "Longitude":"11,012931",
    "LongitudeBefore":"11,013168",
    "MOTCode":5,
    "ModCode":5,
    "NextStop":"STAD:6",
    "Operator":"VAG",
    "ProductIdentifier":"BUS",
    "RealtimeAvailable":1,
    "Timestamp":"2018-11-07T15:13:44+01:00",
    "TimestampPrevious":"2018-11-07T15:12:40+01:00",
    "VehicleIdentifier":"589",
    "X":"11,012931",
    "XPrevious":"11,013168",
    "Y":"49,466061",
    "YPrevious":"49,467044"}

在代码的for循环中,您尝试获取name的{​​{1}}属性,如下所示:

myObj[x]

但是,正如您在上面的JSON中看到的那样,没有for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } 属性,这就是为什么要获取name的原因。

如果您使用正确的属性名称替换上述“ for循环”代码中的undefined,则您的代码将起作用。例如以下内容:

name

我已经对此进行了测试,并且可以正常工作。希望这会有所帮助。