使用Jquery

时间:2017-02-24 19:54:37

标签: javascript jquery ajax

我有输入,我想检查它是否为空。我正在使用维基百科的API来获取信息,这是AJAX的一部分:

$.ajax({
  type: 'GET',
  url: searchedUrl,
  async: false,
  dataType: 'json',
  success: function(data){

      var length = data[1].length;
      var inputValue = $('#searchInput').val();
      console.log(inputValue);

      if (!$('#searchInput').val()){ 
        error = true;
        console.log('err');

      } else {
        if (error = true){
          $('#errorMsg').html('Search error').fadeOut();
        }
        $('.title').css('margin-top', '30px');
        $('#output').removeClass('hidden');
          for (var i = 0; i < length; i++){
            $('#output').prepend('<li><a href='+data[3][i]+'>'+data[1][i]+'</a><br>'+data[2][i]+'</li>');
          }
      }
    },
  error: function(err){
    error = true;
    $('#errorMsg').html('Search error').fadeIn();
  }
});

然而,当它成功时,我希望它检查输入的值是否为空。我使用那个IF条件,但它没有写'错误&#39;在控制台中。如果值为空,它会忽略所有内容。我也试过这样的条件:

if (inputValue !== ''){

// Error;

}

但它不起作用。

PS:这是我的JSFiddle:https://jsfiddle.net/dietic/sdfu967y/

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您正在进行inputValue检查,检查类型和值。这意味着如果nullundefinedinputValue !== '',则您的true将为if (inputValue) { ... }

要防止这种情况发生,只需执行null检查输入值是否为undefined''0Question.query.filter_by(text = text).all()

答案 1 :(得分:1)

我不确定你在这里要做什么。但让我澄清一下。

您的inputValue可以是undefinednull"have something"

如果您致电if(inputValue) // undefined or null or "",它将等于if(false)

如果if(inputValue) // "blah blah"它将等于if(true)

首先,您需要首先检查它是null or undefined,然后如果您想确保它不为空,请致电.length

答案 2 :(得分:0)

感谢您的回答,但我发现它无法正常工作。 在检查此行中是否有数据之前,我试图获取一段数据:

success: function(data){

  var length = data[1].length;
  var inputValue = $('#searchInput').val();
  console.log(inputValue);

在检查输入后它放了var length = data[1].length;并且它有效。

谢谢!