0

在我的应用程序中,我使用 ajax 调用作为 json 数组数据从数据库中获取数据。但有时我可能无法根据条件从数据库中获取数据。我如何检查ajax返回的数组中是否有任何数据。

这是我的代码..

阿贾克斯调用

   $.ajax({ 
        type:'POST',
        url:'user_panel/index',
        data: 'ov_prem_home_id='+home_id,
        dataType: 'json',
        cache: false,
        success: function(dataResponse){
        document.getElementById('ov_prem_title').value=data[0]['title'];
        }
    });

PHP 代码

        $home_id=$_POST[home_id];   
        $ov_result=getPremOveriewData($home_id);
        echo json_encode($ov_result);exit;

我尝试了类似的条件,isset(dataResponse),if(dataResponse=='')但我什么也没得到

4

4 回答 4

0

如果响应为空,它将评估为假,所以只需执行if(dataResponse)

$.ajax({
    type:'POST',
    url:'user_panel/index',
    data: 'ov_prem_home_id='+home_id,
    dataType: 'json',
    cache: false,
    success: function(dataResponse){
        if (dataResponse) {
            document.getElementById('ov_prem_title').value=data[0]['title'];
        }
    }
});
于 2013-10-23T12:06:12.587 回答
0
$.ajax({    
    type:'POST',
    url:'user_panel/index',
    data: 'ov_prem_home_id='+home_id,
    dataType: 'json',
    cache: false,
    success: function(dataResponse){
    if(typeof dataResponse != 'undefined' && dataResponse.length > 0 )
      document.getElementById('ov_prem_title').value=data[0]['title'];
    }
});
于 2013-10-23T12:06:53.377 回答
0

如果你想要从 Javascript 端检查数据,你可以使用类似的东西:

$.ajax({    
    type:'POST',
    url:'user_panel/index',
    data: 'ov_prem_home_id='+home_id,
    dataType: 'json',
    cache: false,
    success: function(dataResponse){
       if (data && dataResponse.length>0 && dataResponse[0]['title'])
       {
           document.getElementById('ov_prem_title').value=dataResponse[0]['title'];
       }
       else
       {
           //Empty
       }
    }
});
于 2013-10-23T12:07:06.997 回答
0

简单的方法:

success: function(dataResponse){
   if(!dataResponse){ 
      // its empty
   }
}

您还可以通过在 PHP 中执行此操作来为自己提供更多保障:

echo (empty($ov_result) ? null : json_encode($ov_result));exit;

null如果$ov_result为空,这将不返回任何内容 ( )

于 2013-10-23T12:05:17.677 回答