Ajax提交表单数据的几种方式

来源:互联网 发布:淘宝上靠谱的日代 编辑:程序博客网 时间:2024/06/03 19:24

总结一下Ajax提交表单数据的几种方式

第一种方式:手工填写所有表单数据

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title>    <script type="text/javascript">        $(function(){            $.ajax({                url:'xxxx',                type:'post',                dataType:'json',                data:{                    'p1':$('#p1'),                    'p2':$('#p2')                },                success:function(result){                    //回调函数                }            });        });    </script></head><body>    <form id="myForm" action="">        <input id="p1" name="p1" value="p1"/>        <input id="p2" name="p2" value="p2"/>        <input id="btn" type="button" value="提交"/>    </form></body></html>

第二种方式:$(‘#myform’).serialize( );

注意:这时表单的按钮的type不可以是submit,否则自提交数据,也就是自动刷新;
当时做的一个功能是: 在数据列表的第二页点击一条数据修改,修改成功后,显示修改成功,页面还要停留在第二页,不能回到第一页,所以就不能刷新网页,不然就回到第一页了;而用Ajax的serialize()提交表单,如果input的type为submit,提交时就会自动刷新,回到第一页,所以,用serialize()提交表单的时候最好把type改为button

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title>    <script type="text/javascript">        $(function(){            $.ajax({                url:'xxxx',                type:'post',                dataType:'json',                data:$("#myForm").serialize(),                success:function(result){                    //回调函数                 }            });        });    </script></head><body>    <form id="myForm" action="">        <input id="p1" name="p1" value="p1"/>        <input id="p2" name="p2" value="p2"/>        <input id="btn" type="button" value="提交"/>    </form></body></html>

第三种方式:使用jQuery Form插件提供的ajaxSubmit()函数
没怎么使用过,在网上找了一下代码,估计需要引用一下js文件

$('#myform').ajaxSubmit({type: 'GET/POST',url: 'xx.php',dataType: 'json',success: fn,clearForm: true,resetForm: true});  //此函数会自动把选定的表单进行序列化并异步提交