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

标签 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脚本中看到的,我有一个alert(),它应该弹出hello,但它永远不会弹出

最佳答案

早上好!

我认为关于您的代码有几件事要说。首先,您的 submit 函数:

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

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

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

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

这可以让浏览器做你想做的事情,而不是自己处理提交。

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

下一步:ajax 调用。

你做了很多正确的事情,但也做了一些重要的事情。看下面的结构:

$.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);
     } 
}}); 

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

第三件事:名称检查后真正的提交怎么样?

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

想一想:

  1. 让用户填写您的表单
  2. 让他点击提交按钮
  3. 防止浏览器的默认行为并构建 FormData 并将所有值放入其中
  4. 准备 Ajax 调用
  5. FormData 与您的 ajax 调用一起发送到您的服务器
  6. 在服务器端处理名称检查和所有其他事务
  7. 回答请求
  8. 评估您的成功函数中的答案

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

关于javascript - 如何在不使用ajax提交表单的情况下将文本值发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033457/

相关文章:

javascript - 对多种产品使用一个 Google Checkout 按钮

javascript - 将 popover 放入 td

javascript - 使用javascript为单词添加样式

javascript - 将javascript对象写入 Node 中的文件

jquery - CSS 缩放图像并填充容器

jquery - 在 jQuery 中生成下拉菜单的年份

javascript - 使用下拉选择器更改/覆盖 PHP 变量

javascript - 将动态 javascript 变量附加到 HTML 标记。 InnerHTML 和 insertAdjacentHTML 均不正确

javascript - Rest API 显示 [object Object] 而不是数组对象

html - 如何将内部 DIV 对齐到外部 DIV 的中心