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

总结一下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
});  
//此函数会自动把选定的表单进行序列化并异步提交
  • 10
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值