無名

大猫咪与小狮子

导航

jquery Serialize

使用ajax时,常常需要拼装input数据为'name=abc&sex=1'这种形式,用JQuery的serialize方法可以轻松的完成这个工作!

jQuery ajax - serialize() 方法定义和用法

serialize() 方法通过序列化表单值,创建URL 编码文本字符串。

您可以选择一个或多个表单元素(比如input 及/或文本框),或者form 元素本身。

序列化的值可在生成AJAX 请求时用于URL 查询字符串中。

jQuery ajax - serialize() 方法语法

$(selector).serialize()

jQuery ajax - serialize() 方法详细说明

.serialize() 方法创建以标准URL 编码表示的文本字符串。它的操作对象是代表表单元素集合的jQuery 对象。

jquery ajax - serialize() 方法表单元素有几种类型:

<form>

  <div><inputtype="text" name="a" value="1" id="a"/></div>

  <div><inputtype="text" name="b" value="2" id="b"/></div>

  <div><inputtype="hidden" name="c" value="3" id="c"/></div>

  <div>

    <textareaname="d" rows="8" cols="40">4</textarea>

  </div>

  <div><selectname="e">

    <optionvalue="5" selected="selected">5</option>

    <optionvalue="6">6</option>

    <optionvalue="7">7</option>

  </select></div>

  <div>

    <inputtype="checkbox" name="f" value="8"id="f" />

  </div>

  <div>

    <inputtype="submit" name="g" value="Submit"id="g" />

  </div>

</form>

.serialize() 方法可以操作已选取个别表单元素的jQuery 对象,比如<input>, <textarea> 以及<select>。不过,选择<form> 标签本身进行序列化一般更容易些:

$('form').submit(function() {

  alert($(this).serialize());

  return false;

});

输出标准的查询字符串:

a=1&b=2&c=3&d=4&e=5

jQuery ajax - serialize() 方法注意:只会将”成功的控件“序列化为字符串。如果不使用按钮来提交表单,则不对提交按钮的值序列化。如果要表单元素的值包含到序列字符串中,元素必须使用name 属性。

以上jQuery ajax - serialize() 方法基础内容转W3C,下面讲解下用jQuery ajax - serialize() 方法时候出现的几种常见问题下面分享给大家

请看下面例子如:

<form id="form1">

<input name="name1"type="text" value="pipi" />

<input name="name2"type="radio" value="1" checked/>boy

<input name="name2"type="radio" value="0"/>girl 

<textareaname="name3">test</textarea>

</form>

使用:$("#form1").serialize();

结果:name1=pipi&name2=1&name3=test

用jQuery ajax - serialize()方法还有个问题

如果是下面的情况:

<form id="form1">

    <inputname="name" type="text" value="pipi" />

    <inputname="blog" type="text" value="blue submarine"/>

</form>

使用:$("#form1").serialize();

结果:name1=pipi&blog=blue+submarine

就是如何能让+号变回空格呢?

最后还有一个问题,如下所示:

<form id="form1">

   <inputname="length" type="text" value="pipi" />

   <inputname="blog" type="text" value="blue submarine"/>

</form>

使用:$("#form1").serialize();

结果:blog=blue+submarine 没法出现length=pipi

原因是length是js数组的属性关键字,出现冲突了,将name改为其他非冲突字符串即可

posted on 2013-06-08 13:03  xiezhengcai  阅读(2265)  评论(0编辑  收藏  举报