无法读取null的属性

无法读取null的属性

本文介绍了未捕获的TypeError:无法读取null的属性"0"-传单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过JS + AJAX更新我的传单地图,但是传单向我返回错误Uncaught TypeError:无法在leaflet.js:5上读取null的属性"0"

I'm trying update my leaflet map via JS + AJAX, but leaflet return me an error Uncaught TypeError: Cannot read property '0' of null on leaflet.js:5

我有一个函数,它从服务器获取数据,一切正常,当我调用函数 getData 时,我获取了数据,函数 printRoute 将数据写入了"test"元素,但是 L.polyline([... 仍然返回错误.数据( xhttp.responseText 的输出)"格式正确,即 L.polyline 需求([[49.999319,13.897081],[49.997681,13.905933],...,[49.996141,13.913901],[49.994664,13.921527])

I have function, which get data from server, everything works, when I call function getData, I get data and function printRoute writes data to "test" element, but L.polyline([... still returns error. Data ( output of xhttp.responseText ) are in right format, which L.polyline needs( [ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ], ... , [ 49.996141, 13.913901 ], [ 49.994664, 13.921527 ] )

当我仅在服务器上,仅使用PHP而没有AJAX时,一切正常.拜托,你有什么提示吗?

When I do it only on server, only with PHP, without AJAX, everything works fine.Please, do you have some hints?

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 属性实际上是String类型.折线函数正在寻找一个数组数组,但经过了单个字符串的数组.

The coordinates being past from the server are in array notation, however the xhttp.responseText property is actually a String type. The polyline function is looking for an array of arrays but gets past an array of a single string.

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

代替

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

配置服务器以返回正确的json对象来解决此问题.

configure the server to return a proper json object to fix this.

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

using eval('[' + xhttp.responseText + ']') to convert your string into an array is not recomemeded as it creates a security vulnerabilitie in your code.

这篇关于未捕获的TypeError:无法读取null的属性"0"-传单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:35