通过Ajax提交表单而非提交按钮:序列化失效及按钮位置疑问
问题解答
嘿,我来帮你排查并解决这两个问题:
1. 为什么serialize()没有输出?
这是核心问题:jQuery的serialize()方法是依靠表单元素的name属性来收集数据的,你当前的所有<input>标签只设置了id,却没有添加对应的name属性,所以序列化时找不到可处理的表单字段,自然没有输出内容。
解决方法非常简单:给每个需要序列化的<input>都加上name属性,比如:
<input type="text" class="form-control" id="name" name="name" aria-describedby="name_help" placeholder="Name"> <input type="text" class="form-control" id="address_line_1" name="address_line_1" aria-describedby="address_line_1_help" placeholder="Address Line 1"> <!-- 其他input标签同理添加对应name属性 -->
加上name后,$('#customer_form').serialize()就能正常输出类似name=xxx&address_line_1=xxx的序列化字符串了。
2. 按钮是否需要放在<form>元素内?
其实没有强制要求,但你当前的写法是完全没问题的:
- 你给按钮设置了
type="button",这会阻止它触发表单的默认提交行为(如果是type="submit"就会自动提交表单),正好符合你用Ajax提交的需求。 - 按钮放在表单内或者外,都可以绑定点击事件发起Ajax请求,不会影响功能实现。
修改后的完整代码示例
HTML部分(添加name属性)
<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" name="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" name="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" name="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" name="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>
JavaScript部分(无需修改,保持即可)
$(document).ready(function(){ $('#create').click(function(event) { console.log('foo'); alert($('#customer_form').serialize()); event.preventDefault(); }); });
内容的提问来源于stack exchange,提问作者M.E.
相关产品推荐
相关产品推荐

