简体   繁体   English

如何检查从 ajax 返回的数据是否为 json 是否为空 object

[英]How to check if data returned from ajax as json is empty object or not

I have set this script for checking if the email address exists in the DB or not:我已经设置了这个脚本来检查数据库中是否存在 email 地址:

function checkemail(){
            var e = document.getElementById("email").value;
            if(e != ""){
                document.getElementById("emailstatus").innerHTML = 'checking ...';
                $.ajax({
                    type:'get',
                    url:'{!! URL::to('checkEmailExists') !!}',
                    data:{'email':e},
                    success:function(data){
                        // console.log(data);

                        if(Object.keys(data).length === 0)
                        {
                            document.getElementById("emailstatus").style.color = "red";
                            document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
                        }else{
                            document.getElementById("emailstatus").style.color = "green";
                            document.getElementById("emailstatus").innerHTML = e + " is OK";
                        }
                    },
                    error:function(){

                    }
                });
            }
        }

So the code works fine but the only problem is comes from this condition checking which always returns TRUE :所以代码工作正常,但唯一的问题是来自这个总是返回TRUE的条件检查:

if(Object.keys(data).length === 0)

Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data) ):基本上,如果我输入数据库中不存在的 email 地址,这将作为data返回( console.log(data)的结果):

{}

Otherwise, it will return this obj:否则,它将返回这个对象:

{
    "id": 1,
    "name": "Myname",
    "email": "myemail@yahoo.com",
    "email_verified_at": null,
    "created_at": "2022-02-09T05:49:27.000000Z",
    "updated_at": "2022-02-09T05:49:27.000000Z"
}

So I need to properly check if the returned object is empty or not.所以我需要正确检查返回的 object 是否为空。

But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.但看起来if(Object.keys(data).length === 0)没有正确检查该条件,因为它始终为,因此[email] is OK语句出现在页面上。

So how to properly check if the returned object is empty or not?那么如何正确判断返回的object是否为空呢?

Object.keys should work: Object.keys 应该可以工作:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

I suggest you double-check the params sent to the success function.我建议你仔细检查发送给success function 的参数。

You can check for a specific property, if it's not there then it will be undefined , meaning you didn't get a success response.您可以检查一个特定的属性,如果它不存在那么它将是undefined ,这意味着您没有得到成功响应。

Combine undefined with ||结合undefined|| to get a "value if not set", gives:要获得“未设置值”,给出:

success:function(data) {
    var success = (data.id || 0) > 0;

You could just check for if (data.id == undefined) but there are a number of caveats when comparing with undefined您可以只检查if (data.id == undefined)但在与undefined进行比较时有许多注意事项

See below solution that have worked for me:请参阅以下对我有用的解决方案:

$.ajax({
        url: url,
        type: 'POST',
        data: { par1: value1, 
                par2: value2 },
        dataType: 'JSON',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        success: function(response) 
                 {                                     
                   if(Object.keys(response).length > 0) 
                   {
                     //there is valid returned response    
                   }
                    else
                    {
                      //no response keys returned                            
                    }
                },
                error: function (x, h, r) {
                    //deal with errors....
                }
            })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM