【问题标题】:Uncaught TypeError: Cannot read property '0' of null - leaflet未捕获的类型错误:无法读取 null 的属性“0” - 传单
【发布时间】: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


【解决方案1】:

从服务器过去的坐标是数组符号,但是xhttp.responseText 属性实际上是一个字符串类型。 polyline 函数正在寻找一个数组数组,但通过了单个字符串的数组。

['[ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ]']

而不是

[[ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ]]

配置服务器返回一个正确的 json 对象来解决这个问题。

不推荐使用eval('[' + xhttp.responseText + ']') 将您的字符串转换为数组,因为它会在您的代码中创建一个安全漏洞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2016-05-08
    • 1970-01-01
    • 2022-01-19
    • 2021-12-01
    • 2022-07-02
    • 2022-06-14
    相关资源
    最近更新 更多