检查 AJAX 返回的 JSON 数据是否已设置


check the ajax returned json data is set or not

在我的应用程序中,我使用 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=='')这样的条件,但我什么也没得到

如果你想要从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
       }
    }
});

如果响应为空,则计算结果为 false,因此只需执行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'];
        }
    }
});
$.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'];
    }
});

简单的方法:

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

你也可以通过在PHP中这样做来为自己投保更多:

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

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