一,表单序列化
脚本:
<script type="text/javascript">
$().ready(function () {
var test = $('#form1').serialize();
$("#divShow").html(test);
});
</script>
form元素:
<form action="/" id="form1" runat="server">
<input type="checkbox" name="check" checked="" value="Man" />
<select name="select">
<option>Shanghai</option>
<option selected="selected">GuangZhou</option>
</select>
<input type="text" name="txtName" value="Tom" />
<input type="submit" value="submit" />
</form>
<div id="divShow">
</div>
序列化结果
__VIEWSTATE=%2FwEPDwULLTE2MTY2ODcyMjlkZLQXkPeYUElxhKg0ySH6gzFHVZn%2FlKb2cDBL0QQRQC0L&check=Man&select=GuangZhou&txtName=Tom
jQuery中,表单form序列化的函数 $(“#formID”). serialize();
序列化要求:是表单中的元素必须有name属性,无name属性的元素将不显示。
序列化中特别之处:
1,<input type="hidden" name="hidden" value="secrecy" />
序列化结果是hidden=secrecy
2,<select name="select">
<option>ShangHai</option>
<option selected="selected">GuangZhou</option>
</select>
序列化结果是select=GuangZhou
若select中option的属性值不等于selected,序列化结果是select=ShangHai
3, <input type="checkbox" name="check" checked="checked" value="Man" />
序列化结果是check=Man
checkbox中的checked属性不等于checked,序列化时将不显示。
4,若form表单有runat=”server”,序列化的结果会多出个__VIEWSTATE=……,否则的话,不会多出它。
二,JavaScriptSerializer(JavaScript序列化)
public partial class Test4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Student obj = new Student { ID = "B0905", Name = "Tom" };
List<Student> list = new List<Student> { new Student { ID = "B0906", Name = "张三" }, new Student { ID = "B0907", Name = "李四" } };
StringBuilder buildObj = new StringBuilder();
StringBuilder builderList = new StringBuilder();
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.Serialize(obj, buildObj);
serializer.Serialize(list, builderList);
ClientScript.RegisterClientScriptBlock(this.GetType(), "s1", "<script>alert('" + buildObj.ToString() + "')</script>", false);
ClientScript.RegisterClientScriptBlock(this.GetType(), "s2", "alert('" + builderList.ToString()+"')", true);
}
}
class Student
{
public string ID { get; set; }
public string Name { get; set; }
}
弹出左右框。
RegisterClientScriptBlock 是后台注册在前台 body 中脚本的方法。
JavaScriptSerializer 能够将数据格式化成JSON格式。