未捕获的ReferenceError:未定义数据点。从api调用json数据时

时间:2018-08-17 09:56:19

标签: javascript api leaflet

我正在尝试从具有JSON格式数据的api调用变量数据点。 我收到以下错误:

未捕获的ReferenceError:未定义数据点

我在这里使用了变量。

     for (var i=0; i<datapoint.length; i++) {

            var lon = datapoint[i][2];
            var lat = datapoint[i][3];
            var popupText = String(datapoint[i][2]);
            var markerLocation = new L.LatLng(lat, lon);
            var marker = new L.marker(markerLocation);
            marker.addTo(map).bindPopup(popupText);
            marker.setOpacity(0.001);
        }

这是我如何调用api:

<script src="http://example.com/vx1/xloc.php?qty=100"></script>

JSON对象:

{"datapoint":[{"intensity":92,"latitud":"18.52","longitud":"82.4767"},{"intensity":68,"latitud":"17.7375","longitud":"82.8347"}]}

3 个答案:

答案 0 :(得分:2)

您获取的值有误。请从此代码中删除并相应更新

fetch('http://example.com/vx1/xloc.php?qty=100')
  .then((response) => response.json())
  .then((response) => {
        let datapoint = response.datapoint;
        for (let i=0; i<datapoint.length; i++) {

            let lon = datapoint[i]["latitude"];
            let lat = datapoint[i]["longitude"];
         //rest of the code
        }
  });

答案 1 :(得分:1)

您需要使用AJAX从API中获取json

// create the ajax call
httpRequest = new XMLHttpRequest();

// set the callback
httpRequest.onreadystatechange = () => {

    // this if mean the call was responded
    if (httpRequest.readyState === XMLHttpRequest.DONE) {

        // this if tell you the request was successful
        // the possible status are the http status code
        if (httpRequest.status === 200) {
            datapoint = JSON.parse(httpRequest.responseText).datapoint;
            // do your things with datapoint
        }
    }
}

// send the request
httpRequest.open('GET', 'http://example.com/vx1/xloc.php?qty=100');
httpRequest.send();

有关http status code的更多信息


如果有人要进行编辑以添加jQuery的版本,那不客气(我对jQuery不好)(起点:$.ajax documentation

答案 2 :(得分:1)

jQuery版本:

$.getJSON('http://example.com/vx1/xloc.php?qty=100', function(data) {
   $.each (data, function (i, item) {
   // Do things with item.datapoint
    });
});