首页 > 解决方案 > 长度函数抛出未捕获的错误

问题描述

执行此代码时出现错误。该代码运行良好,但引发了未捕获的错误。我应该担心这个吗?

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
   response = JSON.parse(this.responseText);     
}   

document.getElementById(type).options.length = 0;

for (var i = 0; i < response.length ; i++) {
  var option = document.createElement("OPTION");
  option.innerHTML = response[i];
  option.value = response[i];
  ddlEnvType.options.add(option);
}

document.getElementById(type).disabled = false;

};
xmlhttp.open("POST","sample.php?condition=" +x.value +"&type=" +type,true);
xmlhttp.send();
}

标签: javascriptjqueryajax

解决方案


document.getElementById(type).options.length = 0;

上面的行抛出错误,因为.length用于返回length并且不能用于为其分配值。

在 for 循环中

i<response.length

但响应不是一个数组,它是一个 JSON 对象,这是导致错误的原因

response = JSON.parse(this.responseText); 

推荐阅读