Previously, I introduced the preliminary understanding of Ajax in Understanding Ajax. This article will introduce how to use it conveniently in ASP.NET Ajax, the first one is of course using jQuery's ajax, which is powerful and easy to operate. The second one is to use .NET encapsulated ScriptManager.
Related free learning recommendations: ajax(Video)
This is the simplest way. First, briefly understand the syntax of jQuery ajax. The most commonly used calling method is this: $.ajax({settings}) ; There are several commonly used settings. All parameters and their explanations can be found in jQuery official API documentation
1. type: request method get/post
2. url: requested Uri
3. async: whether the request is asynchronous
4. headers: customized header parameters
5. data: parameters sent to the server
6. dataType: Parameter format, common ones include string, json, xml, etc.
7. contents: A "string/regular expression" map that determines how to parse the response
8. contentType: Send The content encoding type of the data sent to the server. Its default value is "application/x-www-form-urlencoded; charset=UTF-8".
9. success: The handle called after the request is successful.
10.error: The handle called after the request fails
If you haven’t used jQuery’s ajax before, it feels a bit confusing. Let’s take a look at a simple example
First use Visual Studio to create a new WebApplication, introduce jQuery.js into the project, and then add two pages, Default.aspx as a test
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %> <!DOCTYPE html > <html> <head runat="server"> <title>Ajax</title> <script src="jQuery.js" type="text/javascript"></script> <style type="text/css"> html, body, form { width: 100%; height: 100%; padding: 0px; margin: 0px; } #container { margin: 100px; height: 300px; width: 500px; background-color: #eee; border: dached 1px #0e0; } </style> </head> <body> <form id="form1" runat="server"> <p id="container"> <input type="button" value="Test Ajax" onclick="testGet()" /> <br /> </p> <script type="text/javascript"> function setContainer(text) { document.getElementById("container").innerHTML += ('<br/>' + text); } function testGet() { $.ajax({ type: 'get', url: 'NormalPage.aspx', async: true, success: function (result) { alert(result); }, error: function () { setContainer('ERROR!'); } }); } </script> </form> </body> </html>
NormalPage.aspx is used as the request page, no processing is done first. In the JavaScript in the Default.aspx page, you can see that the testGet function uses jQuery Ajax sends a get request to Normal.aspx. The unwritten parameters use jQuery default parameters. This call does not use any parameters. It simply sends a request to the Normal.aspx page. If the request is successful, all responses will be alerted (that is, the success method parameters: result, jQuery will pass the responseText into the success method as the first parameter), and if the request fails, a line of error text will be added to p. If everything is normal, you can see a dialog box popping up on the page, and the content in the dialog box is the Normal.aspx page Content
A simple get request is completed. Such results are generally of little use and are not the intention of ajax. The main purpose of using Ajax is to use JavaScript to send asynchronously to the server. Specific requests to obtain server-related data, such as asking the server for weather, then obtaining weather data, updating the page, rather than obtaining the entire page. In other words, using Ajax itself is to get rid of the pattern of updating the entire page to update page data, just We only need the server to give us data, which requires calling a specific method on the server side.
We need to modify NormalPage.aspx at this time and add several methods to it for Default.aspx test call
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Web { public partial class NormalPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = Request.QueryString["action"]; Response.Clear(); //清除所有之前生成的Response内容 if (!string.IsNullOrEmpty(action)) { switch (action) { case "getTime": Response.Write(GetTime()); break; case "getDate": Response.Write(GetDate()); break; } } Response.End(); //停止Response后续写入动作,保证Response内只有我们写入内容 } private string GetDate() { return DateTime.Now.ToShortDateString(); } private string GetTime() { return DateTime.Now.ToShortTimeString(); } } }
Then add a new method to Default.aspx and modify the button’s onclick method to the newly written function
function testGet2() { $.ajax({ type: 'get', url: 'NormalPage.aspx', async: true, data:{action:'getTime'}, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
The testGet2 function is in Some modifications were made based on the testGet function. First, the success method was changed and the obtained response was written to the page; then the data parameter was added to the request, and the request sent an action: getTime key-value pair to the server. In get In the request, jQuery will convert this parameter into a url parameter. The above writing method has the same effect as this writing method
function testGet3() { $.ajax({ type: 'get', url: 'NormalPage.aspx?action=getTime', async: true, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
Look at the execution effect, this is the monitoring result of Chrome
如果调试我们发现这个请求调用的服务器页面NormalPage.aspx的GETime方法,并且response中只包含对有用的数据,如果把请求中参数的值改为getDate,那么就会调用对应GetDate方法。
这样向一个页面发送请求然后在Load事件处理程序中根据参数调用不同方法,清除Response,写入Response,终止Response,而且传入的参数局限性太大,好业余的赶脚,看看专业些解决方法。为project添加一个General Handler类型文件,关于HttpHandler相关内容本文不做详细解释,只需知道它可以非常轻量级的处理HTTP请求,不用走繁琐的页面生命周期处理各种非必需数据。
Handler.ashx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using Newtonsoft.Json;namespace Web { /// <summary> /// Summary description for Handler /// </summary> public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { Student stu = new Student(); int Id = Convert.ToInt32(context.Request.Form["ID"]); if (Id == 1) { stu.Name = "Byron"; } else { stu.Name = "Frank"; } string stuJsonString= JsonConvert.SerializeObject(stu); context.Response.Write(stuJsonString); } public bool IsReusable { get { return false; } } } }
关于这个类语法本文不做详细说明,每次发起HTTP请求ProcessRequest方法都会被调用到,Post类型请求参数和一再Request对象的Form中取得,每次根据参数ID值返回对应json对象字符串,为了展示json格式数据交互,需要为项目引入json.net这一开源类库处理对象序列化反序列化问题,然后创建一个Student类文件
Student.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Web { public class Student { public int ID { get; set; } public string Name { get; set; } } }
看看页面如何处理
function testPost() { $.ajax({ type: 'post', url: 'Handler.ashx', async: true, data: { ID: '1' }, success: function (result) { setContainer(result); var stu =eval ('('+result+')'); setContainer(stu.ID); setContainer(stu.Name); }, error: function () { setContainer('ERROR!'); } }); }
结果是这个样子的
上面代码向Handler.ashx发送一Post请求,比且带有参数{ID:’1’},可以看到结果,如果用调试工具可以发现,得到的result是一个json格式的字符串,也就是往Response写的对象序列化后的结果。这样就实现了比较专业些的方式调用Ajax,但是有一个问题依旧存在,HttpHandler会自动调用ProcessRequest方法,但是也只能调用该方法,如果想调用不同方法只能像普通页面那样传递一个参数表明调用哪个方法,或者写不同的Handler文件。
微软向来很贴心,看看微软怎么处理上面的困惑,那就是利用WebService,WebService配合SCriptManager有客户端调用的能力,在项目中添加一个Webservice文件
WebService.asmx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Web { /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public Student GetStudent(int ID) { if (ID == 1) { return new Student() { ID = 1, Name = "Byron" }; } else { return new Student() { ID = 2, Name = "Frank" }; } }
[WebMethod] public string GetDateTime(bool isLong) { if (isLong) { return DateTime.Now.ToLongDateString(); } else { return DateTime.Now.ToShortDateString(); } } } }
代码中加黄的code默认是被注释掉的,要想让客户端调用需要把注释去掉,Service中定义了两个方法,写个测试方法让客户端调用第一个方法根据参数返回对应对象,首先需要在页面from内加上ScriptManager,引用刚才写的WebService文件
Default.aspx
<form id="form1" runat="server"> <asp:ScriptManager ID="clientService" runat="server"> <Services> <asp:ServiceReference Path="~/WebService.asmx" /> </Services> </asp:ScriptManager> <p id="container"> <input type="button" value="Test Ajax" onclick="testPost2()" /> <br /> </p>...
然后添加JavaScript测试代码
function testPost2() { Web.WebService.GetStudent(1, function (result) { setContainer(result.ID); setContainer(result.Name); }, function () { setContainer('ERROR!'); }); }
测试代码中需要显示书写WebService定义方法完整路径,WebService命名空间.WebService类名.方法名,而出入的参数列表前几个是调用方法的参数列表,因为GetStudent只有一个参数,所以只写一个,如果有两个参数就顺序写两个,另外两个参数可以很明显看出来是响应成功/失败处理程序。看看执行结果:
观察仔细会发现使用ScriptManager和WebService组合有福利,在WebService中传回Student对象的时候并没有序列化成字符串,而是直接返回,看上面图发现对象已经自动转换为一json对象,result结果可以直接操作,果真非常贴心。而上一个例子中我们得到的response是一个json字符串,在客户端需要用eval使其转换为json对象。
ScriptManager+WebSefvice调用ajax带来了很大的便利性,但同时牺牲了很多灵活性,我们没法像jQuery那样指定很多设置有没有两全其美的办法呢
jQuery调用Handler几乎完美了,但是不能处理多个方法,上面例子我们可以发现WebService可以实现这一功能,那么能不能jQUery调用WebService的不同方法呢?答案是肯定的,试一试用jQuery调用刚才WebService定义的第二个方法。写一个测试函数
function testPost3() { $.ajax({ type: 'post', url: 'WebService.asmx/GetDateTime', async: true, data: { isLong: true }, success: function (result) { setContainer($(result).find('string').text()); }, error: function () { setContainer('ERROR!'); } }); }
调用方式没有多大变化,简单依旧,只要把URL改为WebService路径+需要调用的方法名,然后把参数放到data里就可以了。我们看看结果:
通过上图可以看到,jQuery调用WebService默认会返回一个XML文档,而需要的数据在
json.net是一个开源的.net平台处理json的库,可以序列化Dictionay嵌套等复杂对象,关于其简单使用有时间会总结一下,可以自codeplex上得到其源码和官方说明。本文的源代码可以点击这里获得。
其他相关免费学习推荐:js视频教程
The above is the detailed content of Using Ajax under ASP.NET. For more information, please follow other related articles on the PHP Chinese website!