如何处理 getJSON 调用上的“未捕获类型错误:无法设置未定义的属性'prop'”
How to handle "Uncaught TypeError: Cannot set property 'prop' of undefined" on a getJSON call?
我有一个调用REST Web服务并获得JSON答案的HTML。当我输入错误的参数时,我可以毫无问题地捕获错误,但有时 JSON 上的某些结果为空。我怎样才能抓住这种情况?
我的网页:
<div id="divname"></div>
我的JavaScript:
$.getJSON(URL, function(data) {
$('#divname').html(data.result[0].dest[0].pred[0].time);
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); $('#divname').html('Wrong Parameter.'); })
.always(function() { alert('getJSON request ended!'); });
一个好的 JSON 结果是这样的:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{
"pred": [{
"time": 1461348846,
"sec": 102,
"min": 1,
"string11": "514-String",
"string12": "Some String",
"string13": "Some other String",
"number": 0
}]
}]
}]
}
但有时,当没有数据可显示时,我得到这样的东西:
{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{"pred":[]}]
}]
}
我在铬控制台中得到以下内容:
Uncaught TypeError: Cannot set property 'time' of undefined
我明白为什么这会失败,但我不知道如何捕获此错误以显示在失败的 HTML 上。
添加对 pred 长度的检查:
$.getJSON(URL, function(data) {
if (data.result[0].dest[0].pred.length) {
$('#divname').html(data.result[0].dest[0].pred[0].time);
} else {
// handle the case with empty pred here
}
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); $('#divname').html('Wrong Parameter.'); })
.always(function() { alert('getJSON request ended!'); });
或者,检查 pred[0] 是否未定义:
$.getJSON(URL, function(data) {
if (typeof data.result[0].dest[0].pred[0] !== 'undefined') {
$('#divname').html(data.result[0].dest[0].pred[0].time);
} else {
// handle the case with empty pred here
}
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); $('#divname').html('Wrong Parameter.'); })
.always(function() { alert('getJSON request ended!'); });
相关文章:
- Jqx图表给出错误错误:
属性高度=“-1”的负值无效 - 谷歌地图 API 错误:属性<航点>::中的错误
- 未捕获的类型错误:属性'$'对象[object Window]的
- 错误“属性'日期选择器'在带有打字稿的类型'IAugmentedJQuery'上不存在
- 类型错误属性 然后是未定义的
- 挖空引用错误 - 属性在存在时未定义
- “语法错误:属性列表后缺少}” 如何使Javascript符号证明
- 错误:
属性宽度=“NaN” 6d3.v3.min.js:1 的值无效: 属性 x=“NaN” - Ajax 和 JS on select_taf;语法错误:属性列表后缺少 }
- 获取错误语法错误:属性列表 url 后缺少 }:http://localhost/mcportal/public/pos
- Google Maps JavaScript : 未捕获错误: 属性
- 类型错误:属性 1 不可配置,无法删除
- Javascript/HTML错误“属性”selectReason“的值为null或未定义,而不是函数对象
- Mootools'未捕获的类型错误:属性'容器'对象#<对象>不是函数'添加
- 错误:
属性残雪=“NaN"在dimple.js - D3.js错误:
属性用于折线图 - 错误:d3.v4.min.js:3错误:<属性宽度:期望长度,"
- SVG路径错误"d"属性
- 错误:
d =“属性.饼状图 - 未捕获的类型错误:属性'fn'对象[object DOMWindows]的不是函数