开发者

How to handle a blank row from the database?

开发者 https://www.devze.com 2023-03-25 11:25 出处:网络
I have the following script which works as long as it is returned data: $(document).ready(function() {

I have the following script which works as long as it is returned data:

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: 'notifications.asmx/GetNotifications',
        data: '{strUser: "pqr"}',
  开发者_JAVA技巧      contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function( notifications ) {
            if( notifications !== null ) { //<-- this makes no difference
                 alert( notifications.d[0].text ) ;
            } else {
                alert ( "null" );
            }
        },
        error: function(xhr, status, error) {
                 var err = eval("(" + xhr.responseText + ")");
                 alert(err.Message) ;
        }
    });
});

If data is not returned, I get the error:

Uncaught TypeError: Cannot read property 'text' of undefined

I have tried wrapping it in various if statements checking for null values, but that does not make any difference.


It sounds like it's notifications.d[0] that is undefined so you should be checking that in your if statement rather than notifications.

if( notifications.d[0] ) { //<-- this should now work
    alert( notifications.d[0].text ) ;
} else {
    alert ( "null" );
}


Try if( notifications !== undefined )


Try the following test:

if(notifications.d != null && notifications.d.length > 0) {
    alert(notifications.d[0].text);
} else {
    alert("null");
}


Try this

success: function( notifications ) {
            if( notifications && notifications.d && (notifications.d.length > 0) ) { //<-- this makes no difference
                 alert( notifications.d[0].text ) ;
            } else {
                alert ( "null" );
            }
        },


Don't check for null - it'll be undefined if anything. It's generally much easier to just check for:

if (notifications) { //do something with notifications }

but be aware that this will not work if notifications is 0 or "".


You can shorten it with

if (notifications && notifications.d && notifiations.d[0]) {
   // notifications.d[0] exists
}


try

if( notifications.d[0].text ) { //<-- this makes no difference
    alert( notifications.d[0].text ) ;
} else {
    alert ( "null" );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消