![](/img/trans.png)
[英]Check if AJAX response data if is empty or null than don't show in output
[英]Check if AJAX response data is empty/blank/null/undefined/0
我有查詢數據庫后返回 HTML 的 jQuery AJAX 函數。 根據查詢的結果,該函數將根據需要返回 HTML 代碼或不返回任何內容(即空白)。
我需要有條件地檢查數據何時為空白。
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: associated_buildsorprojects_form,
success:function(data){
if(!data){
//if(data="undefined"){
//if(data==="undefined"){
//if(data==null){
//if(data.length == 0){
//if ( data.length != 0 ){
//if(data===0){
//if(data==="0"){
alert("Data: " + data);
}
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
我嘗試了各種條件,但沒有一個能正確檢查數據。 根據我的發現,空白警報消息並不意味着數據是
如果不是這些事情,我如何有條件地檢查產生空白警報消息的數據?
Felix Kling在問題的評論部分提供了以下正確答案:
if (!$.trim(data)){
alert("What follows is blank: " + data);
}
else{
alert("What follows is not blank: " + data);
}
//if(data="undefined"){
這是一個賦值語句,而不是一個比較。 此外, "undefined"
是一個字符串,它是一個屬性。 檢查它是這樣的: if (data === undefined)
(沒有引號,否則它是一個字符串值)
如果未定義,您可能會返回一個空字符串。 您也可以嘗試檢查if (!data)
等falsy
值
if(data.trim()==''){alert("Nothing Found");}
這對我有用.. page.php 上的 PHP 代碼
$query_de="sql statements here";
$sql_de = sqlsrv_query($conn,$query_de);
if ($sql_de)
{
echo "SQLSuccess";
}
exit();
然后AJAX代碼有波紋管
jQuery.ajax({
url : "page.php",
type : "POST",
data : {
buttonsave : 1,
var1 : val1,
var2 : val2,
},
success:function(data)
{
if(jQuery.trim(data) === "SQLSuccess")
{
alert("Se agrego correctamente");
// alert(data);
} else { alert(data);}
},
error: function(error)
{
alert("Error AJAX not working: "+ error );
}
});
注意:必須從 PHP 接收“SQLSuccess”這個詞
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: associated_buildsorprojects_form,
success:function(data){
// do console.log(data);
console.log(data);
// you'll find that what exactly inside data
// I do not prefer alter(data); now because, it does not
// completes requirement all the time
// After that you can easily put if condition that you do not want like
// if(data != '')
// if(data == null)
// or whatever you want
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
如果您使用響應而不是使用響應,那么您將獲得從PHP回顯的所有內容。 希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.