weixin_33686714 2018-11-07 14:00 采纳率: 0%
浏览 58

读取JSON并插入HTML表

In the following code, I try to show stings of the source in a HTML table. The problem at this is, that instead of the string I see "undefined". Thanks in advance!

    <!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条回答 默认 最新

  • weixin_33701564 2018-11-07 14:28
    关注

    I tested your code and I have looked at the JSON that is being returned in the response. An example of an object being returned is as follows:

        {"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"}
    

    In the for loop in your code you are attempting to get a name property of myObj[x] as follows:

    for (x in myObj) {
        txt += "<tr><td>" + myObj[x].name + "</td></tr>";
    }
    

    However as you can see in the JSON above, there is no name property and this is why you are getting undefined.

    If you replace name in the above "for loop" code with a correct property name then your code will work. For example the following:

    for (x in myObj) {
        txt += "<tr><td>" + myObj[x].CurrentStop + "</td></tr>";
    }
    

    I have tested this and it works. Hope this helps.

    评论

报告相同问题?