dongtan2017
2014-10-31 12:36
浏览 104
已采纳

如何避免AJAX成功函数中的未定义错误消息

Sometimes, data returned from the server is not defined which results in the following appearing on my page:

<p id="element">undefined</p>

My AJAX success function:

success: function( data ) {
    $( '#element' ).text( data.message )
}

PHP handler:

$response = array()

// Some logic which may assign data to $response['message']

echo json_encode( $response );
die;

Is there a way to suppress such undefined messages?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongluni0568 2014-10-31 12:39
    已采纳

    Depending on what you want, you can show message only if it was provided

    if (data.message) {
        $('#element').text(data.message)
    }
    

    or maybe show default message if server returns nothing (or empty string):

    $('#element').text(data.message || 'No message.')    
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drfqfuhej48511519 2014-10-31 12:38
    success: function( data ) {
    
        if( data.message !== undefined )
            $( '#element' ).text( data.message )
    
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题