jQuery ajax序列化函数

参数序列化$.param()

举例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    personObj = new Object();
    personObj.firstname = "John";
    personObj.lastname = "Doe";
    personObj.age = 50;
    personObj.eyecolor = "blue"; 
    $("button").click(function(){
        $("div").text($.param(personObj));
    });
});
</script>
</head>
<body>

<button>Serialize object</button>

<div></div>

</body>
</html>
View Code

上述返回的结果是:firstname=John&lastname=Doe&age=50&eyecolor=blue

$.param将对象或者数组序列化,序列化的值可以用于AJAX请求时的URL查询字符串

$.param(object,trad)

 

ParameterDescription
object必须,指定一个要被序列化的对象亦或数组
trad

可选,是否使用传统的参数序列化模式,默认false,注意要在jQuery1.4以上才能使用

 

$(document).ready(function(){
    personObj ={
           a: {
                one: 1,
                two: 2,
                three: 3
             },
            b: [ 1, 2, 3 ]
        }
    $("button").click(function(){
        document.body.innerHTML=(decodeURIComponent($.param(personObj,true)));
    });
});

上述传统序列化显示的结果是:a=[object+Object]&b=1&b=2&b=3

如果是

 $("div").text(decodeURIComponent($.param(personObj)));

将true去掉,将成为a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

 

表单序列化$.serialize()

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div").text($("form").serialize());
    });
});
</script>
</head>
<body>

<form action="">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>

<button>Serialize form values</button>
<div></div>
</body>
</html>

结果是:FirstName=Mickey&LastName=Mouse

$(selector).serialize()

序列化表单值并创建一个编码过的url文本

你可以选择一个或更多的表单元素(比如input和textarea),或者表单元素本身

序列化的值可以被用于在创建一个AJAX请求的时候,组合URL查询字符串

 

表单序列化$.serializeArray()

将表单元素序列化成对象数组

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var x = $("form").serializeArray();
        console.log(x);      
    });
});
</script>
</head>
<body>

<form action="">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
</form>

<button>Serialize form values</button>
<div id="results"></div>
</body>
</html>

控制台输出的结果是

语法格式为:

$(selector).serializeArray()

 

转载于:https://www.cnblogs.com/RachelChen/p/5433734.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值