jQuery ajax - serialize() 方法

来源:互联网 发布:eclipse端口号 编辑:程序博客网 时间:2024/05/18 00:14

1、实例

输出序列化表单值的结果:

$("button").click(function(){  $("div").text($("form").serialize());});

$('#submitButton').click(function(){ addCard($('#addCard')); });function addCard(frm) {addCard_before();$.ajax({type:"POST",url:"/card/addCard.jhtml",datatype:"json",data:frm.serialize(),success: function (data) {if (data.code == 'success') {alert('操作成功!');window.open('/card/index.jhtml','_self');} else {alert(data.msg);}},       error: function(data) {           alert("操作出错!");       }});}<form id="addCard" action="addCard.jhtml"> <tr>  <td>     <font color="red">*</font>年卡名称:  </td>  <td>     <input type="text" name="cardname" id="cardname" />  </td>  <td>     <font color="red">*</font>年卡类型:  </td>  <td>    <label><input name="cardtype" type="radio" value="1" id="cardtype1" style="width:20px;margin:1px;" onclick="cardTypeChange();" checked/>学段卡</label>    <label><input name="cardtype" type="radio" value="2" id="cardtype2" style="width:20px;margin:1px;" onclick="cardTypeChange();"/>学科卡</label>  </td> </tr>


2、定义和用法

serialize() 方法通过序列化表单值,创建 URL 编码文本字符串。
您可以选择一个或多个表单元素(比如 input 及/或 文本框),或者 form 元素本身。
序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中。
语法
$(selector).serialize()
3、详细说明
.serialize() 方法创建以标准 URL 编码表示的文本字符串。它的操作对象是代表表单元素集合的 jQuery 对象。

表单元素有几种类型:

<form>  <div><input type="text" name="a" value="1" id="a" /></div>  <div><input type="text" name="b" value="2" id="b" /></div>  <div><input type="hidden" name="c" value="3" id="c" /></div>  <div>    <textarea name="d" rows="8" cols="40">4</textarea>  </div>  <div><select name="e">    <option value="5" selected="selected">5</option>    <option value="6">6</option>    <option value="7">7</option>  </select></div>  <div>    <input type="checkbox" name="f" value="8" id="f" />  </div>  <div>    <input type="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

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

http://www.w3school.com.cn/jquery/ajax_serialize.asp

0 0
原创粉丝点击