【问题标题】:how to submit form using jquery ajax? [duplicate]如何使用 jquery ajax 提交表单? [复制]
【发布时间】:2017-01-03 22:47:27
【问题描述】:

基本上我有一个表单,里面有几个带有提交按钮的文本框,问题是当我提交表单时它只发送用户名框值而不发送其他文本框的值。

我正在使用 servlet。

我的代码:

$(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        Form_submition();
    });

  });
  function Form_submition(){
      var formData = {
            'firstname': $('input[name=FirstName]').val(),
                'username': $('input[name=UserName]').val(),
              };
              $.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) {

                  console.log(data);
                });
  }

这就是我创建表单和文本框的方式:

 <form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">


        <div id="Registeration_Firstname_Div" class="Registeration_Firstname_Div">
            <input type="text" id="Registeration_Firstname_box" class="Registeration_Firstname_box"
            placeholder="First name" name="FistName" maxlength="30" onblur="checkTextField(this, 'firstnameerror_div');" onclick="textboxfocus(this)"/>
        </div>


        <div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
            <input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
                placeholder="" name="UserName" maxlength="30" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" onclick="textboxfocus(this)"/>
        </div>

</form>
<div class="Registration_Submit_Div">
            <input type="submit" value="Sign up" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
        </div>

我输出接收数据的 servlet 代码:

 PrintWriter out = response.getWriter();

    String str = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

    System.out.println(str);

我在服务器中获得的输出只是具有价值的用户名,仅此而已

【问题讨论】:

  • 尝试删除第 11 行末尾的 ,(第一个代码部分)。最后一个对象属性末尾不需要逗号。
  • @yuriy636 除非他运行的是非常旧版本的 IE,否则它应该可以工作。
  • 如果这是问题所在,他将不会得到任何结果,因为它会抱怨语法错误。
  • 我刚刚删除了,没有任何变化仍然只得到用户名,我在最新版本的 chrome、firefox 和 opera 上尝试了这个
  • 查看“网络”选项卡,检查它所说的正在发送的请求参数。

标签: javascript jquery ajax forms servlets


【解决方案1】:

以防万一其他人遇到这个问题。我更改了我的 jquery 代码,而不是通过它的名称获取框到 ID。这解决了我的问题!

var formData = {
     'firstname': $('#Registeration_Firstname_box').val(),
     'username': $('input[name=UserName]').val()
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多