如何避免用户在 ajax 帖子中输入空字符串

How to avoid user from entering empty string in ajax post

本文关键字:输入 字符串 何避免 用户 ajax      更新时间:2023-09-26

我有一个jquery ajax帖子,当用户在消息框中按回车键时,这个ajax会触发。 但是当用户写 Nothing 并按 Enter 时,这个 ajax 被触发并返回一些东西。 但是如何从用户那里捕获空字符串?

cliKeyPressed : function(e) {
        if(typeof e === "undefined" ) e = window.event;
        if(e.keyCode == 13) {
          var previousLine = "";
          if($('#terminal').text()!== ""){
            previousLine = $('#terminal').text();
            previousLine = previousLine.replace("you entered: ", " ");
          }
          var inputData = $(e.currentTarget).val();
          $('#terminal').text(previousLine + "'r'n" + inputData + "'r'n");
                    AjaxPost(inputData);
        }
AjaxPost : function(data) {
      $.ajax({
       type : "POST",
       url : "/api/user",
       datatype : "application/json",
       contentType: " text/plain",
       data : dataAttribute,
       success : function(data) {
       },
       error : function(error) {
       },

你已经在这样做了。只需将 AjaxPost 的调用移到 if 语句中:

if(typeof e === "undefined" ) e = window.event;
    if(e.keyCode == 13) {
        var previousLine = "";
        if($('#terminal').text() !== "" && $(e.currentTarget).val() !== ""){
            previousLine = $('#terminal').text();
            previousLine = previousLine.replace("you entered: ", " ");
            var inputData = $(e.currentTarget).val();
            $('#terminal').text(previousLine + "'r'n" + inputData + "'r'n");
            AjaxPost(inputData);
        }
    }
}