AJAX JQuery 调用后台方法返回值(不刷新页面)
(1)无参数返回值(本人亲试返回结果不是预期结果)
javascript方法:
$(function () {
//无参数返回值
$("#btn_Ajax1").click(function () {
$.ajax({
type: "Post",
//方法所在页面和方法名
url: "Ajax_Test.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;
});
后台方法:
//[System.Web.Services.WebMethod()]
//不带参数
[WebMethod()]
public static string getValueByAjaxNoParms()
{
string ddd = "返回 GAGAHJT";
return ddd.ToString();
}
(2)带参数返回值
javascript方法:
//带参数
$("#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;
});
后台方法:
//带参数
[WebMethod]
public static string getValueByAjaxByParms(string str, string str2, string str3)
{
return str + str2 + str3;
}
(3)返回数组
javascript方法:
//返回数组
$("#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;
});
后台方法:
//返回数组
[WebMethod]
public static List<string> getArrayByAjax()
{
List<string> li = new List<string>();
for (int i = 0; i < 10; i++)
li.Add(i + "");
return li;
}
(4)返回hashtable
javascript方法:
//返回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;
});
后台方法:
//Hashtable
[WebMethod]
public static Hashtable geHashtableByAjax(string key, string value)
{
Hashtable hs = new Hashtable();
hs.Add("www", "yahooooooo");
hs.Add(key, value);
return hs;
}
(5)返回DataTable
javascript方法:
//返回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;
});
后台方法:
//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();
}
(5)返回DataTable
javascript方法:
//返回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")
}
});
});
});
后台方法:
//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);
}
前台数据转换方法
//解析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;
}
后台数据转换方法
#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