【转】Jquery -Ajax 入门练习 Jquery.Ajax 调用后台函数,获取DataTable Json,Asp.net
直接上图=============最后拷贝源码(图片清楚)
=========================================================================================================
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax_Test.aspx.cs" Inherits="Ajax_Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Jquery -Ajax 入门联系 Jquery.Ajax 调用后台函数,获取DataTable Json,Asp.net</title>
<script language="javascript" type="text/javascript" src="JQquery/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
//无参数返回值
//===============================================
$("#btn_Ajax1").click(function () {
$.ajax({
//要用post方式
type: "Post",
//方法所在页面和方法名
url: "Ajax_Test.aspx/getValueByAjaxNoParms",
//url: "Ajax_ResponseText.aspx/getValueByAjaxNoParms", //其他页面
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (XMLHttpRequest) {
$('#show').text("正在查询");
},
success: function (data) {
//返回的数据用data.d获取内容
alert(data.d);
},
error: function (err) {
alert(err);
}
});
//禁用按钮的提交
return false;
});
//===============================================
//带参数
$("#btn_Ajax2").click(function () {
$.ajax({
type: "Post",
url: "Ajax_Test.aspx/getValueByAjaxByParms",
//方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字
data: "{'str':'我是','str2':'XXX','str3':'是不是?'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//返回的数据用data.d获取内容
alert(data.d);
},
error: function (err) {
alert(err);
}
});
//禁用按钮的提交
return false;
});
//===============================================
//返回数组
$("#btn_Ajax3").click(function () {
$.ajax({
type: "Post",
url: "Ajax_Test.aspx/getArrayByAjax",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//插入前先清空ul
$("#show").html("");
//递归获取数据
$(data.d).each(function () {
//插入结果到li里面
$("#show").append("<li>" + this + "</li>");
});
alert(data.d);
},
error: function (err) {
alert(err);
}
});
//禁用按钮的提交
return false;
});
//===============================================
//返回hashtable
$("#btn_Ajax4").click(function () {
$.ajax({
type: "Post",
url: "Ajax_Test.aspx/geHashtableByAjax",
//记得加双引号 T_T
data: "{ 'key': 'haha', 'value': '哈哈!' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//debugger;
alert("key: haha ==> " + data.d["haha"] + "\n key: www ==> " + data.d["www"]);
},
error: function (err) {
alert(err + "err");
}
});
//禁用按钮的提交
return false;
});
//===============================================
//返回DataTable(json)1
$("#btn_Ajax5").click(function () {
$.ajax({
type: "Post",
url: "Ajax_Test.aspx/geDataTableByAjax1",
data: "{'str':'我是','str2':'XXX','str3':'是不是?'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
//你可以 alert(data.d)看数据返回的格式
data = jQuery.parseJSON(data.d); // JSON再次转换为Table 形式;
//可以是用 data[Row][Column].toString()来读取值;Row:第几行 Column:数据字段
//alert(data[0]["ID"].toString() + ";"+data[0]["Name"].toString() + ";"+data[0]["Address"].toString());
t = "<table border='1'>";
$.each(data, function (i, item) {
t += "<tr>";
t += "<td>" + item.ID + "</td>";
t += "<td>" + item.Name + "</td>";
t += "<td>" + item.Address + "</td>";
t += "</tr>";
})
t += "</table>";
$("#show").html(t);
//$('#Div1').html(BuildDetails(data));
},
error: function (err) {
alert(err + "err");
}
});
//禁用按钮的提交
return false;
});
//===============================================
//返回DataTable(json)2
$("#btn_Ajax6").click(function () {
$.ajax(
{ type: "post",
url: "Ajax_Test.aspx/geDataTableByAjax2",
//data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
var mydts = data.d.mytablename; //这里也可以接受类似 DataSet 的对象;
$('#Div1').html(BuildDetails(mydts));
$('#Div2').html(BuildTable(mydts));
},
failure: function () {
alert("error")
}
});
});
//=================================================
});
//解析DataTable(非真正的Table)
function BuildDetails(dataTable) {
var content = [];
for (var row in dataTable) {
for (var column in dataTable[row]) {
content.push("<tr>");
content.push("<td><b>");
content.push(column);content.push("</td></b>"); content.push("<td>") ;
content.push(dataTable[row][column]);
content.push("</td>");content.push("</tr>");
}
}
var top = "<table border='1' class='dvhead'>";
var bottom = "</table>";
return top + content.join("") + bottom;
}
function BuildTable(dataTable) {
var headers = [];
var rows = [];
//column
headers.push("<tr>");
for (var column in dataTable[0])
headers.push("<td><b>" + column + "</b></td>");
headers.push("</tr>");
//row
for (var row in dataTable) {
rows.push("<tr>");
for (var column in dataTable[row]) {
rows.push("<td>");
rows.push(dataTable[row][column]);
rows.push("</td>");
}
rows.push("</tr>");
}
var top = "<table border='1' class='gvhead'>";
var bottom = "</table>"; return top + headers.join("") + rows.join("") + bottom;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input value="无参数" type="button" id="btn_Ajax1" />
<input value="带参数" type="button" id="btn_Ajax2" />
<input value="返回数组" type="button" id="btn_Ajax3" />
<input value="返回Hashtable" type="button" id="btn_Ajax4" />
<input value="返回DataTable(返回Json)" type="button" id="btn_Ajax5" />
<input value="返回DataTable(返回类似Table)" type="button" id="btn_Ajax6" />
<div id="show">
</div>
<div id="Div1">
</div>
<div id="Div2">
</div>
</div>
</form>
</body>
</html>
*******************************************************************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data; //命名空间
using System.Web.Services;//命名空间
using System.Collections;//命名空间
using System.Web.Script.Serialization;//命名空间
public partial class Ajax_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//[System.Web.Services.WebMethod()]
//不带参数
[WebMethod()]
public static string getValueByAjaxNoParms()
{
string ddd = "返回 GAGAHJT";
return ddd.ToString();
}
//带参数
[WebMethod]
public static string getValueByAjaxByParms(string str, string str2, string str3)
{
return str + str2 + str3;
}
//返回数组
[WebMethod]
public static List<string> getArrayByAjax()
{
List<string> li = new List<string>();
for (int i = 0; i < 10; i++)
li.Add(i + "");
return li;
}
//Hashtable
[WebMethod]
public static Hashtable geHashtableByAjax(string key, string value)
{
Hashtable hs = new Hashtable();
hs.Add("www", "yahooooooo");
hs.Add(key, value);
return hs;
}
//Json
//在前台通过jQuery.parseJSON(data.d); 转换为类似Table
[WebMethod]
public static string geDataTableByAjax1(string str, string str2, string str3)
{
DataTable dt = new DataTable();
dt.TableName = "表名";
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = i.ToString();
dr["Name"] = "JSON" + i.ToString();
dr["Address"] = "中国-北京-海淀" + i.ToString() + "号";
dt.Rows.Add(dr);
}
string strss=Dtb2Json(dt).ToString();
return strss.ToString();
}
//json
[WebMethod]
public static Dictionary<string, object> geDataTableByAjax2()
{
DataTable dt = new DataTable();
dt.TableName = "mytablename";
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = i.ToString();
dr["Name"] = "JSON" + i.ToString();
dr["Address"] = "中国-北京-海淀" + i.ToString() + "号";
dt.Rows.Add(dr);
}
return DatToJson(dt);
}
#region DataTable转Json
public static string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
#endregion
#region Json转DataTable
public static DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize<ArrayList>(json);
DataTable dtb = new DataTable();
if (dic.Count > 0)
{
foreach (Dictionary<string, object> drow in dic)
{
if (dtb.Columns.Count == 0)
{
foreach (string key in drow.Keys)
{
dtb.Columns.Add(key, drow[key].GetType());
}
}
DataRow row = dtb.NewRow();
foreach (string key in drow.Keys)
{
row[key] = drow[key];
}
dtb.Rows.Add(row);
}
}
return dtb;
}
#endregion
#region DataTable转Json(非Json)
//类似 前台jQuery.parseJSON(dt)函数
private static Dictionary<string, object> DatToJson(DataTable table)
{
Dictionary<string, object> d = new Dictionary<string, object>();
d.Add(table.TableName, RowsToDictionary(table));
return d;
}
private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
{
List<Dictionary<string, object>> objs = new List<Dictionary<string, object>>();
foreach (DataRow dr in table.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
for (int i = 0; i < table.Columns.Count; i++)
{
drow.Add(table.Columns[i].ColumnName, dr[i]);
}
objs.Add(drow);
}
return objs;
}
#endregion
}