hasOwnProperty不起作用

时间:2016-01-03 10:35:50

标签: javascript angularjs json http

我从服务器获得了一个JSON对象({error:true})。

我尝试检查对象是否包含密钥"错误"如果密钥存在,函数hasOwnProperty将返回false

这是我的代码:

$http({
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
        url: '/Modules/Partners/Mailing/SendMail.ashx',
        data: $.param({ contact: JSON.stringify(contact), body: partnerObject.mailTemplate.longValue, title: "" }),
        method: 'POST'
    })
    .success(function (data, status, headers, config) {
        console.log(data);
        console.log(data.hasOwnProperty('error'));

       if (data.hasOwnProperty('error')) {
           deferred.reject(contact);
       } else {
           deferred.resolve(contact);
       }
       //console.log(data)

    })
    .error(function (data, status, headers, config) {
        deferred.reject(contact);
    });

在控制台中我可以看到该对象包含"错误" hasOwnProperty('error')的密钥返回false

enter image description here

6 个答案:

答案 0 :(得分:3)

我认为问题出在您收到的JSON对象上。实际上,密钥不是error而是'error'。尝试查看data.hasOwnProperty("'error'")是否有效。

答案 1 :(得分:1)

您的success方法会收到String个数据,而不是JSON

.success(function (data, status, headers, config) {
    var result = angular.fromJson(data);

    if (result.hasOwnProperty('error')) {
        deferred.reject(contact);
    } else {
        deferred.resolve(contact);
    }
    //console.log(data)
})

BTW:如果它是JSON,在控制台中,你会看到:

enter image description here

答案 2 :(得分:0)

您是否尝试过使用if(data && data.error)代替if (data.hasOwnProperty('error'))

可能是因为error属性是继承的。查看有关hasOwnProperty和继承属性here

的更多信息

答案 3 :(得分:0)

检查从服务器发送的数据的内容类型。应该是' application / json'然后它隐式转换为javascript对象。 检查使用"类型数据"它一定是"对象"否则,如果它的字符串,那么你需要使用JSON.parse

将其解析为对象

答案 4 :(得分:0)

我不知道为什么但是返回对象就好了 JsonSerializer.Serialize( “{\” 错误\ “:真}”);

而不是 JsonSerializer.Serialize( “{ '错误':真}”); 要么 JsonSerializer.Serialize( “{错误:真}”);

解决我的问题

答案 5 :(得分:0)

您可以使用in运算符检查对象/数组上是否存在属性。 可以这样使用"error" in data //将返回true

相关问题