有時候我們使用Ajax連結一般處理程式需要傳回多個值,然而這些資料并非在一個查詢表内,此時便想到構造一個虛拟的DataTable,這樣就可以傳回多個值了(當然有很多辦法,這是其中一種 )。
首先我們需要準備一個 script 和一個 ashx 檔案。
在script中寫一個ajax用于接收傳回來的資料,代碼如下。
<script type="text/javascript">
$(function () {
$.ajax({
type: "post", //送出方式
url: "/ashx/PersonnelRegistrationForm.ashx", //一般處理程式的路徑
data: { corpName: corpName, corpCode: corpCode }, //向背景傳入的值
success: function (data) { //傳回成功後将要做的事,這裡是傳回一個表
var datainfo = $.parseJSON(data);
alert(datainfo[0].OrderNo);
alert(datainfo[0].RowGuid);
alert(datainfo[0].ResultNum);
},
error: function () {
alert('系統發生錯誤');
}
});
})
</script>
然後在名為PersonnelRegistratinForm一般處理程式進行資料處理,然後構造所需要的值将其傳回。
#region 構造傳回的表
DataTable table = new DataTable(); //構造表
DataColumn column1 = new DataColumn("ResultNum", Type.GetType("System.Int32")); //構造列及所對應的類型
DataColumn column2 = new DataColumn("OrderNo", Type.GetType("System.String"));
DataColumn column3 = new DataColumn("RowGuid", Type.GetType("System.String"));
table.Columns.Add(column1); //将列添加到table表中
table.Columns.Add(column2);
table.Columns.Add(column3);
DataRow dr = table.NewRow(); //table表建立行
dr["ResultNum"] = person_result;
dr["OrderNo"] = OrderNo;
dr["RowGuid"] = t_ROWGUID;
table.Rows.Add(dr); //将資料加入到table表中
string json = SerializerHelper.ToJsonString(table); //序列化json對象
context.Response.Write(json);
context.Response.End();
#endregion
構造table時可以使用簡便寫法:
DataTable table = new DataTable(); //構造表
table.Columns.Add("ResultNum", Type.GetType("System.Int32"));
table.Columns.Add("OrderNo", Type.GetType("System.String"));
table.Columns.Add("RowGuid", Type.GetType("System.String"));
DataRow dr = table.NewRow(); //table表建立行
dr["ResultNum"] = person_result;
dr["OrderNo"] = OrderNo;
dr["RowGuid"] = t_ROWGUID;
table.Rows.Add(dr); //将資料加入到table表中
這樣前台的ajax就可以擷取到傳回過去的table了。當然别忘記引用命名空間
using System.Data;
using System.Data.SqlClient;
using System.Text;