Я пытаюсь вызвать переменные datapoints из api, которые имеют данные в формате JSON. Я получаю следующую ошибку:
Uncaught ReferenceError: datapoint не определен
Здесь я использовал переменную.
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"}]}
Вы неправильно оцениваете значения. Извлеките лист из этого кода и обновите свой код соответственно
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
}
});
вам нужно использовать AJAX, чтобы получить json из API
// 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)
Версия jQuery:
$.getJSON('http://example.com/vx1/xloc.php?qty=100', function(data) {
$.each (data, function (i, item) {
// Do things with item.datapoint
});
});