0

这是 ajax 函数,我希望当数据为nullundefined输出时(#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);

          }
        });
    });
  });
4

3 回答 3

0

感谢您的所有评论和答案,我了解了其他答案的更多内容:) 我添加了行 $("#access").val("") 并修复了问题。

      success: function(data){
          $("#access").val("");
          var str = data.access.replaceAll(/\|/g, ',');
          var result = str.substring(1, str.length - 1);

          $("#access").val(result);

      }
于 2017-08-19T09:44:14.273 回答
0

我建议添加一个简单的通用函数来检查空/未定义,因为这对于您项目的其他部分也很方便。通用函数如下所示:-

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
     }

我希望这可以解决障碍

于 2017-08-19T08:25:47.533 回答
0

只需添加一个条件来检查数据是否存在

If(data) {
    var str = data.access.replaceAll(/\|/g, ',');
    var result = str.substring(1, str.length - 1);

    $("#access").val(result);
}
于 2017-08-19T08:06:47.957 回答