【问题标题】:null jSON object, error Uncaught TypeError: Cannot read property 'length'null JSON 对象,错误未捕获类型错误:无法读取属性“长度”
【发布时间】:2012-10-11 15:22:01
【问题描述】:

我有一个脚本,我通过 JSON 获取一些数据,就像:

$.getJSON('phpfile', function(data) { ...

当我收到一些数据时它工作得很好,但是当它为空时,我得到下一个错误:

未捕获的类型错误:无法读取 null 的属性“长度”

我得到这个错误的地方是这样一行:

if(data==null){
 //actions if the JSON is doesnt give me data
}else{
 //actions if I get data
}

我想要控制JSON何时发送数据,我该怎么做?

编辑:当数据是空对象,当 json 没有得到任何数据时,我得到了 $.each(data, function(key, val) { 的错误。

提前致谢

【问题讨论】:

  • What I want is to control when JSON sends data or not, how can I do it ? 服务器根据您服务器端代码中的逻辑向您发送 JSON 数据或无响应。
  • 当我没有 JSON 数据时,它返回 null 而不是数据
  • 如果没有数据,为什么不返回null
  • 您认为在出现错误时进行处理是解决您问题的方法吗? try ($.getJSON('phpfile', function(data) { ... ) catch(e) { ... when error .... }
  • 当“数据”为null时,这些“动作”究竟是什么?

标签: javascript json getjson


【解决方案1】:
$.getJSON('phpfile', function handleSuccess(data) {
    if(!data){ 
          //handle if null or undefined
    }else{
         //actions if I get data
    }
    }).error(function handleErrorCase(){
        //handle error i.e. your server returning something other 200 or not json
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-18
    • 2019-01-28
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多