DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> Jquery 組合form元素為json格式,asp.net反序列化
Jquery 組合form元素為json格式,asp.net反序列化
編輯:JQuery特效代碼     
作者:敖士偉 Email:[email protected] 轉載注明作者
說明: 1、js根據表單元素class屬性,把表單元素的name和value組合為json格式;用表單元素class屬性可以針對性地組合JSON數據。
2、後端ASP.NET用JavaScriptSerializer反序列化為對象實列。
3、好處:簡化了前端數據讀取與後端數據賦值。
代碼如下:
function GetJSONStr(class_name) {
var a = [];
//文本框
$("." + class_name).filter(":text").each(function(i) {
//alert(this.name);
//alert(this.value);
a.push({ name: this.name, value: this.value });

});
//下拉列表
$("." + class_name).filter("select").each(function(i) {
//alert(this.name);
//alert(this.value);
a.push({ name: this.name, value: this.value });

});
//單選框
$("." + class_name).filter(":radio").filter(":checked").each(function(i) {
//alert(this.name);
//alert(this.value);
a.push({ name: this.name, value: this.value });
});
//復選框開始
var temp_cb = "";
$("." + class_name).filter(":checkbox").filter(":checked").each(function(i) {
if (temp_cb.indexOf(this.name) == -1) {
temp_cb += this.name + ",";
}

});
var temp_cb_arr = temp_cb.split(",");
var cb_name = "";
var cb_value = "";
for (var temp_cb_i = 0; temp_cb_i < temp_cb_arr.length - 1; temp_cb_i++) {
cb_name = temp_cb_arr[temp_cb_i];
var cb_value_length = $("input[name='" + temp_cb_arr[temp_cb_i] + "']:checked").length;
$("input[name='" + temp_cb_arr[temp_cb_i] + "']:checked").each(function(i) {
if (i == cb_value_length - 1)
cb_value += this.value;
else
cb_value += this.value + ",";

});
//alert(cb_name);
//alert(cb_value);
a.push({ name: cb_name, value: cb_value });
}
//復選框結束


//組合為JSON
var temp_json = "";
for (var json_i = 0; json_i < a.length; json_i++) {
if (json_i != a.length - 1) {
temp_json += '"' + a[json_i].name + '":"' + a[json_i].value + '",';
}
else {
temp_json += '"' + a[json_i].name + '":"' + a[json_i].value + '"';
}
}
return "{" + temp_json + "}";
}

ASP.NET
代碼如下:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string r = Request.Form["msg"];

//{"Name":"MyName1","Single":"one"}

t_json t_json_object = Serializer.Deserialize<t_json>(r);

Response.Write(t_json_object.Name);
Response.End();
}
}

class t_json
{
public DateTime Name;
public string Single;
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved