$.ajax
搞了一下午,本来打算使用ajaxSubmit的,但是总是不执行,现在总结一下$.ajax.
1,(1)首先建立一个页面Default.aspx,其中的body和scirpt如下:
<form id="form1" runat="server"> <div id='divcode'> <img alt='验证码' src='' id='img' /> <input type='text' id='code' /> <input type='button' id='btn' value='发送' /> </div> </form> <script type="text/javascript" language="javascript"> $(function () { $("#btn").click(function () { var code = $("#code").val(); var options = { "url": "Handler.ashx", "type": "post", "dataType": "json" }; alert("提交之前"); $.ajax({ url: "Handler.ashx?code="+code+"",//code通过get发送 type: "post", data: options, dataType: "text", success: function (a) { alert("成功"); alert(a); } }); alert("结束"); }); }); </script>
(2)同目录下建立一个Handler.ashx,代码如下:
public void ProcessRequest (HttpContext context) { context.Response.ContentType ="text/plain"; //响应内容是文本 string url = context.Request.Form["url"];//获取提交的参数 string code = context.Request.QueryString["code"];//url中的参数 if (code=="1") { context.Response.Write(url); return; //根据条件,特殊情况提前返回,相当于向一个方法请求 } context.Response.Write("你好"); context.Response.Write("世界");//两个都会输出 }
2,下面是网上一个例子:
ajax到一个webform.aspx页面或.asmx服务页面,指定url到某个方法。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!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></title> <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> // //无参数调用 $(function () { $('#btn1').click(function () { $.ajax({ type: "POST", //访问WebService使用Post方式请求 contentType: "application/json", //这是发送给服务器的数据格式 url: "Default2.aspx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名 data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到 dataType: 'json', //WebService 会返回Json类型 success: function (result) { //回调函数,result,返回值 alert(result.d); //微软返回的json形式{"d":"你好,世界"} var obj1 = eval(result); //将json字符串转为json对象 alert(obj1.d); //输出: 你好,世界 } }); }); }); //有参数调用 $(function () { $("#btn2").click(function () { $.ajax({ type: "POST", contentType: "application/json", url: "Default2.aspx/GetWish", data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}", dataType: 'json', success: function (result) { alert(result.d); //响应 {"d":"祝您在2009年里 心想事成、万事如意、牛牛牛"} var obj1 = eval(result); alert(obj1.d); } }); }); }); //返回集合(引用自网络,很说明问题) $(function () { $("#btn3").click(function () { $.ajax({ type: "POST", contentType: "application/json", url: "Default2.aspx/GetArray", data: "{i:10}", dataType: 'json', success: function (result) { var obj = eval(result.d); //d对应的是一个数组 响应{"d":[10,9,8,7,6,5,4,3,2,1,0]} alert(obj[1]); $(result.d).each(function () { //遍历所有元素 alert(this); // $('#dictionary').append(this.toString() + " "); alert(result.d.join(" | ")); }); } }); }); }); //返回复合类型 $(document).ready(function () { $('#btn4').click(function () { $.ajax({ type: "POST", contentType: "application/json", url: "Default2.aspx/GetClass", data: "{}", dataType: 'json', success: function (result) { $(result.d).each(function () { //返回 {"d":{"__type":"Default2+Class1","ID":"1","Value":"牛年大吉"}} alert(this); $('#dictionary').append(this['ID'] + " " + this['Value']); alert(result.d.join(" | ")); }); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" id="btn1" value="HelloWorld"/> <input type="button" id="btn2" value="传入参数"/> <input type="button" id="btn3" value="返回集合"/> <input type="button" id="btn4" value=" 返回复合类型"/> </div> <div id="dictionary">dictionary </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.Web.Services; //使用微软自带ajax public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string HelloWorld() { return "你好,世界"; } [WebMethod] public static string GetWish(string value1, string value2, string value3, int value4) { return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4); } /// <summary> /// 返回集合 /// </summary> /// <param name="i"></param> /// <returns></returns> [WebMethod] public static List<int> GetArray(int i) { List<int> list = new List<int>(); while (i >= 0) { list.Add(i--); } return list; } /// <summary> /// 返回一个复合类型 /// </summary> /// <returns></returns> [WebMethod] public static Class1 GetClass() { return new Class1 { ID = "1", Value = "牛年大吉" }; } public class Class1 { public string ID { get; set; } public string Value { get; set; } } }
利用Jquery让返回的各类数据(string、集合(List<>)、类)以Json数据格式返回,为什么要用到result.d
这里我们顺带讲下Json
Json简单讲就是Javascript对象或数组.
Json形式一: javascript对象 { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
Json形式二: javascript数组 [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunterwang", "email": "bbbb"}]
当然javascript 数组和对象可以互相嵌套.如形式一中的"Brett"可以换成一个Js数组或Js对象.那微软的Ajax返回的是哪种形式呢.是第一种.
微软框架默认返回一个 { "d": "后台返回的数据" }
3,ajax到一般应用程序, .ashx文件
用这种方法一般是我们要在ashx文件里手动写好返回的Json格式的数据返回给前台用
ashx 你可以配成Json格式一或Json格式二
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!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></title> <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> $(function () { $("#btn1").click(function () { $.ajax({ type: "POST", url: "Handler.ashx?type=1", dataType: "json", success: function (data) { alert(data.name); //返回的为 Json格式一(Js对象) } }); }); }); $(function () { $("#btn2").click(function () { $.ajax({ type: "POST", url: "Handler.ashx?type=2", dataType: "json", success: function (data) { // 返回的为 Json格式二(Js对象) alert(data[0].name); $(data).each(function (i) { alert(data[i].name); }); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <input type="button" id="btn1" value="返回类型1"/> <input type="button" id="btn2" value="返回类型2"/> </form> </body> </html>
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Web.Script.Serialization; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { JavaScriptSerializer jss = new JavaScriptSerializer(); context.Response.ContentType = "text/plain"; string type = context.Request.QueryString["type"]; if (type == "1") { // 返回的为Json格式一 Js对象 string data = "{\"name\":\"wang\",\"age\":25}"; context.Response.Write(data); return;//下面的不会执行 } if (type == "2") { // 返回的为Json格式二 Js数组 string data = "[{\"name\":\"wang\",\"age\":25},{\"name\":\"zhang\",\"age\":22}]"; context.Response.Write(data); } } public bool IsReusable { get { return false; } } }
使用Dictionary和List来代替拼接字符串。
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Web.Script.Serialization; using System.Collections.Generic; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { JavaScriptSerializer jss = new JavaScriptSerializer(); context.Response.ContentType = "text/plain"; string type = context.Request.QueryString["type"]; if (type == "1") { // 返回的为Json格式一 Js对象 //使用dic不用拼字符串 Dictionary<string, string> dic = new Dictionary<string, string>();// dic.Add("name", "王"); dic.Add("age", "23"); context.Response.Write(jss.Serialize(dic));//输出json形式 //string data = "{\"name\":\"wang\",\"age\":25}"; //context.Response.Write(data); return;//下面的不会执行 } if (type == "2") { // 返回的为Json格式二 Js数组 List<Dictionary<string, string>> list = new List<Dictionary<string, string>>(); Dictionary<string, string> dic1 = new Dictionary<string, string>(); dic1.Add("name", "Wang"); dic1.Add("age", "24"); Dictionary<string, string> dic2 = new Dictionary<string, string>(); dic2.Add("name", "Zhang"); dic2.Add("age", "35"); list.Add(dic1); list.Add(dic2); //string data = "[{\"name\":\"wang\",\"age\":25},{\"name\":\"zhang\",\"age\":22}]"; context.Response.Write(jss.Serialize(list)); } } public bool IsReusable { get { return false; } } }
4
讲到这里基本概念也讲得差不多了. 这里再讲一个够常碰到的例子就是如何把DataTabel转换成Json格式从而好让前台页面调用.
/// <summary> /// DataTable转Json /// </summary> /// <param name="dtb"></param> /// <returns></returns> private 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); }
/// <summary> /// Json转DataTable /// </summary> /// <param name="json"></param> /// <returns></returns> private 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; }
$.ajax({ type: "POST", url: "Handler.ashx", dataType: "json", success: function(data){ var table = $("<table border='1'></table>"); for (var i = 0; i < data.length; i++) { o1 = data[i]; var row = $("<tr></tr>"); for (key in o1) { var td = $("<td></td>"); td.text(o1[key].toString()); td.appendTo(row);} row.appendTo(table); } table.appendTo($("#back")); } });
http://www.cnblogs.com/xiaowu/archive/2011/09/07/2169283.html