Javascript 序列化表单以便通过Ajax发送

Javascript 序列化表单以便通过Ajax发送,javascript,jquery,ajax,forms,Javascript,Jquery,Ajax,Forms,我想通过Ajax发送表单,而不是通过submit按钮 我在下面的代码摘录中定义了表单,后来我定义了jQuery函数来捕获CREATE按钮操作 当我调试这个时,我得到了它 console.log($(“#客户_表单”).serialize()不会抛出任何内容 这是序列化表单的正确方法吗 按钮是否需要位于元素内 以下是使用的代码: HTML: <form id="customer_form" role="form"> <div class="form-group"&g

我想通过Ajax发送表单,而不是通过submit按钮

我在下面的代码摘录中定义了表单,后来我定义了jQuery函数来捕获CREATE按钮操作

当我调试这个时,我得到了它

console.log($(“#客户_表单”).serialize()不会抛出任何内容

  • 这是序列化表单的正确方法吗
  • 按钮是否需要位于
    元素内
以下是使用的代码:

HTML

<form id="customer_form" role="form">

    <div class="form-group">
        <label class="col-sm-4 control-label" for="name">Name</label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="name" aria-describedby="name_help" placeholder="Name">
            <small id="name_help" class="form-text text-muted"></small>
        </div>
    </div>


    <div class="form-group">
        <label class="col-sm-4 control-label" for="address_line_1">Address</label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="address_line_1" aria-describedby="address_line_1_help" placeholder="Address Line 1">
            <small id="address_line_1_help" class="form-text text-muted"></small>
        </div>
    </div>


    <div class="form-group">
        <label class="col-sm-4 control-label" for="address_line_2"></label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="address_line_2" aria-describedby="address_line_2_help" placeholder="Address Line 2">
            <small id="address_line_2_help" class="form-text text-muted"></small>
        </div>
    </div>


    <div class="form-group">
        <label class="col-sm-4 control-label" for="town">Town</label>
        <div class="col-sm-8">
            <input type="text" class="form-control" id="town" aria-describedby="town_help" placeholder="Town">
            <small id="town_help" class="form-text text-muted"></small>
        </div>
    </div>

    <button id="create" class="btn btn-sm btn-primary pull-right m-t-n-xs" type="button"><strong>Save</strong></button>

</form>
$(document).ready(function(){
    $('#create').click(function(event) {
        console.log('foo');
        alert($('#customer_form').serialize());
        event.preventDefault();
    });
});

您只是忘记了在输入中添加name属性:

<input name="nameofInput" .... />
-------^

名称
地址
城镇
保存

它不会序列化任何内容,因为表单的输入没有任何
名称
属性设置
名称
属性,对于表单数据调试,请使用控制台无警报。将官方文档中的action或novalidate属性放在:“要在序列化字符串中包含表单元素的值,该元素必须具有name属性。”添加
name
属性修复了该问题。