jQuery ajax()使用serialize()提交form数据

 

1. jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,我们就可以选择一个或多个表单元素,也可以直接选择form将其序列化,如:(name 属性需要填写)

<form id="form1">
            <input type="hidden" value ="${topicInfo.id}" name="id" id="id" />
            <input type="hidden" value ="${topicInfo.status}" name="status" id="status" />
</form>
$(document).ready(function(){
});

可以把序列化的值传给ajax()作为url的参数,轻松使用ajax()提交form表单了,而不需要一个一个获取表单中的值然后传给ajax(),举例如下:

后台如果接收值为null,把contentType: "application/json"去掉(content-Type定义的是发送至服务器的数据类型,data-Type定义的是服务器返回的数据)

$.ajax({
    type: 'post',
    url: 'your url',
    data: $("#form1").serialize(),
    dataType:"json",
    async:true,//默认异步,false-同步
    success: function(data) {
        // your code
    }
});

参考:https://www.cnblogs.com/lijianda/p/8867555.html

 

 

2. cmdb中一个展示域名的例子

 <div class="ibox-content">
      <form id="asset_form">
            <div class="col-sm-3">
                 <div class="input-group">
                      <input type="text" class="form-control m-b" id="search_input" name="keyword" placeholder="search">
                      <input type="text" style="display: none">
                      <div class="input-group-btn">
                      <button type="button" name="search" class="btn btn-xm btn-primary search_btn" onclick="change_info()">
                          搜索
                      </button>
                      </div>
                 </div>
            </div>  
      </form>
 </div>

<div class="ibox-content"> <div id="replace"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th class="text-center">序号</th> <th class="text-center">域名</th> <th class="text-center">邮箱</th> </tr> </thead> <tbody> {% for i in domains %} <tr> <td class="text-center">{{ forloop.counter }}</td> <td class="text-center">{{ i.name }}</td> <td class="text-center">{{ i.email }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <script type="text/javascript"> function change_info(){ $.ajax({ type: "GET", url: "/assets/domain_search/", data: $("#asset_form").serialize(), // 发送给服务器的字符串或者key:value键值对 success: function (content) { // content表示根据请求,获得的服务端返回的数据 $("#replace").html(content); //返回页面的一个固定写法,https://blog.csdn.net/dreamstar613/article/details/61913970 } }); } </script>

说明: 

其中$("#replace").html(content),我的理解是根据data提供给url的请求参数,获得渲染后的url代码段 <div id="replace">...</div>中的内容,也就是局部渲染

 

posted @ 2021-04-07 11:07  坚强的小蚂蚁  阅读(459)  评论(0编辑  收藏  举报