【发布时间】:2020-02-08 07:17:25
【问题描述】:
我正在尝试通过 JS + AJAX 更新我的传单地图,但传单向我返回一个错误 Uncaught TypeError: Cannot read property '0' of null on leaflet.js:5
我有从服务器获取数据的函数,一切正常,当我调用函数getData 时,我得到数据并且函数printRoute 将数据写入“测试”元素,但L.polyline([... 仍然返回错误。数据(xhttp.responseText 的输出)格式正确,L.polyline 需要
( [ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ], ... , [ 49.996141, 13.913901 ], [ 49.994664, 13.921527 ] )
当我只在服务器上执行此操作时,仅使用 PHP,没有 AJAX,一切正常。 请问,你有什么提示吗?
function getData( url, cFunction, postedData ) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction( this );
}
};
xhttp.open( "GET", url, true );
xhttp.send();
}
function printRoute( xhttp ) {
document.getElementById("test").innerHTML = xhttp.responseText;
var route = L.polyline([ xhttp.responseText ], {color: 'red'} ).addTo(map);
}
【问题讨论】:
-
...
xhttp.responseText在运行时的值是多少?请提供其他人可以运行的MCVE。 -
@IvanSanchez 值为
xhttp.responseText是 LatLong 坐标:[ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ], ... , [ 49.996141, 13.913901 7 6,4 ], [ 49.925], [49.9215], [49.9215], [49.997681] -
可能 responseText 是字符串,试试 eval('[' + xhttp.responseText + ']')
-
鉴于包含数组的字符串基本上是 JSON,为了安全起见,我会使用
JSON.parse()而不是eval()。不要eval()随机的东西,伙计们! -
@luckyape 这对我有帮助。你应该发布你的答案
标签: javascript ajax leaflet