如何处理 getJSON 调用上的“未捕获类型错误:无法设置未定义的属性'prop'”

How to handle "Uncaught TypeError: Cannot set property 'prop' of undefined" on a getJSON call?

本文关键字:错误 属性 prop 类型 未定义 设置 处理 何处理 getJSON 调用      更新时间:2023-09-26

我有一个调用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!'); });