如何在没有使用ajax提交表单的情况下将文本值发送到服务器

时间:2016-08-19 07:31:40

标签: javascript jquery html ajax forms

基本上我有一个表单,并且在该表单中我有一个带有提交按钮的用户名文本框。 现在我想要的是,在我们提交表单之前,我想将文本值发送到服务器,以便服务器可以检查用户名是否未被任何其他用户使用,然后根据我的研究提交表单,我发现本教程很有用https://scotch.io/tutorials/submitting-ajax-forms-with-jquery,尽管本教程使用php进行服务器编码,我正在使用java servlet,但我的ajax脚本永远不会执行。

这是我的代码:

<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">    
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">             </script>

<script>
$(document).ready(function() {

// process the form
$('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'username'             : $('input[name=UserName]').val(),
    };
    alert('hello');
    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : '../postr', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
                    encode          : true
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

 </script>
     <form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
            <input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
                name="UserName" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" maxlength="30" onclick="textboxfocus(this)"/>
        </div>
<div class="Registration_Submit_Div">
            <input type="submit" value="submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
        </div>

</form>
<script>function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
    if (field.value == '') {            
        field.style.borderColor = "red";
        document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
        document.getElementById(errordiv).style.visibility = "visible";
    } else if(!field.value.match(/^[a-zA-Z0-9~`!@#\(\.)]+$/)){
        field.style.borderColor = "red";
        document.getElementById(Notallowcharserror_SPN).style.visibility = "visible";
        document.getElementById(errordiv).style.visibility = "hidden";
    } else {
        field.style.borderColor = "rgb(150,150,150)";
        document.getElementById(errordiv).style.visibility = "hidden";
        document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
    }
}</script>

正如你在我的ajax脚本中看到的那样,我有一个警告()它应该弹出你好,但它永远不会

3 个答案:

答案 0 :(得分:1)

早上好!

我认为您的代码有几个要说的。首先是submit函数:

$('form').submit(function(event) { ... }

在这里,您希望在用户点击按钮时捕获提交事件。一切都很好,但由于您的按钮是type=submit,浏览器也会对点击做出反应并自行处理提交过程。您的功能无法正常调用。为了防止这种情况,您必须在提交时转义表单的默认行为:

$('form').submit(function(event) {
  event.preventDefault();

  $.ajax({ ... });
}

这样可以让浏览器执行您想要的操作,而不是单独处理提交。

现在您的浏览器可以运行您的ajax调用。

下一件事:ajax-call。

你做了很多事情,但有些重要的事情是错误的。请看以下结构:

$.ajax({
     url:      'your_url_to_send_data_to',
     type:     'post', //the method to use. GET or POST
     dataType: 'json',
     data:     data, //your data: {key1:value1, key2:value2}
     success: function(data) { //handle a successfull response (200 OK)
        alert(data);
        //here you can do with your data whatever you want
     },
     error: function(jqXHR, textStauts, errorThrown){ //handle every error. e.g. 500
       alert(textStatus + ': '+errorThrown);
     } 
}}); 

这将处理您的请求的发送和接收。如果服务器返回success,将调用200 OK函数。否则调用error函数。 现在您只需要在服务器端正确处理请求。

第三件事:名称检查后的真实提交是什么?

由于您preventDefault()是默认的浏览器操作,因此必须手动执行此操作。您可以考虑再次触发提交,但是您将在自己编写的函数中再运行一次到目前为止。 因此,你必须自己做。可是等等!你可以在一次通话中结合这两件事!

想一想:

  1. 让用户填写表单
  2. 让他点击提交按钮
  3. 阻止浏览器的默认行为并构建FormData并将所有值放入其中
  4. 准备你的ajax电话
  5. 将带有ajax调用的FormData发送到您的服务器
  6. 处理名称检查以及服务器端的所有其他内容
  7. 回答请求
  8. 在您的success函数
  9. 中评估答案

    注意:在服务器端,您必须打印application/json标题,让浏览器和最后的ajax调用正确处理您的答案。

答案 1 :(得分:1)

由于您需要动态检查用户名可用性,我建议您对 keyup 事件做出反应(注意:我还在下面的演示中添加了对其他可能发生更改的事件的支持)和在固定延迟后安排检查运行。一旦延迟发生,如果用户没有在过渡期间输入任何内容,您可以运行AJAX检查并更新页面;如果用户 在过渡期间输入了某些内容,则您可以直接执行检查。这意味着只要用户停止输入至少硬编码的延迟,就会在每次打字后自动运行检查。

关于提交,我只是允许用户以正常方式提交表单,而不对用户名可用性进行任何最后一秒的AJAX检查。如果用户禁用了JavaScript或以某种方式构建了自己的提交HTTP查询,您仍然必须执行服务器端检查可用性,因此您可以依赖于表单提交时的服务器端检查。动态AJAX检查实际上只对用户提供快速通知,因此只有在用户编辑用户名时才提供,然后立即提交表单。大多数情况下,用户在编辑字段后不会立即提交表单,如果页面上明确指出存在验证失败,则可以依赖大多数用户不提交表单。

var USERNAME_CHECK_DELAY = 800;

var userInputValCount = 0;
var userInputVal = '';

window.handlePossibleUserInputChange = function() {
  let $userInput = $('#userInput');
  let $checkDiv = $('#userCheckLine');
  // if this event doesn't reflect a value change, ignore it
  if ($userInput.val() === userInputVal) return;
  userInputVal = $userInput.val();
  // update the value count
  let userInputValCountCapture = ++userInputValCount; // closure var
  // schedule a potential check run
  setTimeout(function() {
    // only check the current name if the user hasn't typed since the provoking event
    if (userInputValCountCapture !== userInputValCount) return;
    checkUsername();
  },USERNAME_CHECK_DELAY);
  // update the status message
  if ($userInput.val().trim() === '') {
    $checkDiv.text('');
  } else {
    $checkDiv.attr({'class':'checking'});
    $checkDiv.text('checking...');
  } // end if
};

$('#userInput')
  // listen to all events that could cause a change in the input value
  .on('keyup change',handlePossibleUserInputChange)
  // drop is special; the drop event unfortunately fires before the text is changed
  // so we must defer the call until after the text is changed
  // same with mouseup; occurs when clicking the input box X button in IE
  // same with paste via context menu, rather than shortcut (which would trigger keyup)
  .on('drop mouseup paste',function() { setTimeout(handlePossibleUserInputChange); })
;

var lastTaken = true;

window.checkUsername = function() {
  let $checkDiv = $('#userCheckLine');
  let $userInput = $('#userInput');
  // just reset the check line if the input value is empty
  if ($userInput.val().trim() === '') {
    $checkDiv.text('');
    return;
  } // end if
  // ... send ajax call, get result ...
  // (for demo purposes, just invert the previous result)
  let taken = lastTaken = !lastTaken;
  if (taken) {
    $checkDiv.attr({'class':'taken'});
    $checkDiv.text('user name is taken.');
  } else {
    $checkDiv.attr({'class':'notTaken'});
    $checkDiv.text('user name is available.');
  } // end if
};
.taken { color:red; }
.notTaken { color:green; }
.checking { color:grey; font-style:italic; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
  <div>
    <input id="userInput" type="text" placeholder="username"/>
    <span id="userCheckLine"></span>
  </div>
  <input type="submit" value="Submit"/>
</form>

答案 2 :(得分:0)

我认为您应该使用jquery验证的“远程”(https://jqueryvalidation.org/remote-method/),这会检查服务器中字段的验证。你需要jquery。

$("#Registration_Form").validate({
  rules: {
    Registeration_Username_box: {
      required: true,
      remote: {
        url: "check-email.php",
        type: "post"
      }
    }
  }
});