[英]Check if AJAX response data if is empty or null than don't show in output
這是一個ajax函數,我想當數據為null
或undefined
比輸出( #access element
)顯示為空“”(或在輸出為空或未找到時不將任何數據保存在輸出中)
$(function(){
$('#userId').on('keyup', function () {
var value=$(this).val();
$.ajax('/projectname/admin/getUserAccess/' + value,
{
dataType: 'JSON',
success: function(data){
var str = data.access.replaceAll(/\|/g, ',');
var result = str.substring(1, str.length - 1);
$("#access").val(result);
}
});
});
});
只需添加一個條件以檢查是否存在數據
If(data) {
var str = data.access.replaceAll(/\|/g, ',');
var result = str.substring(1, str.length - 1);
$("#access").val(result);
}
我建議添加一個簡單的泛型函數來檢查是否為空/未定義,因為這對於項目的其他部分也很方便。 泛型函數如下所示:
function isEmpty(value) {//Function to check if value is Empty or Null
switch (typeof(value)) {
case "string": return (value.length === 0);
case "number":
case "boolean": return false;
case "undefined": return true;
case "object": return !value ? true : false; // handling for null.
default: return !value ? true : false
}
}
此后,按以下方式更新您的成功:
success: function(data){
if(isEmpty(data)){
$("#access").html(data); //Notice it is Html and not val as you want data displayed
}else {
window.alert('Nothing Returned');//If at all you want an Alert
$("#access").html('');//Sets the $("#access") with nothing to display
}
我希望這可以解決這個障礙
感謝您的所有評論和答案,我了解其他答案的更多信息:)我添加了$(“#access”)。val(“”)行並已解決問題。
success: function(data){
$("#access").val("");
var str = data.access.replaceAll(/\|/g, ',');
var result = str.substring(1, str.length - 1);
$("#access").val(result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.