Ajax 即「Asynchronous Javascript And XML」(異步 JavaScript 和 XML),是指一種建立交互式、快速動態網頁應用的網頁開發技術,無需從新加載整個網頁的狀況下,可以更新部分網頁的技術。javascript
經過在後臺與服務器進行少許數據交換,Ajax 可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。html
1.首先下載ajax.dll,一個百度一下都有下載的!自行查找。前端
2.把ajax.dll導入到工程。右鍵工程-->添加引用--->瀏覽,找到下載好的ajax.dll文件,點擊肯定,這時候在工程目錄下多了一個bin文件夾,裏面就有ajax.dll文件,這證實引入ajax.dll成功了。java
3.設置配置文件web.config。web
在Web.config文件下的 <system.web>節點裏面添加如下代碼便可:ajax
<httpHandlers> <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" /> </httpHandlers>
4.使用演示:4.1首先要對ajax進行註冊。 在aspx.cs代碼中的Page_Load方法裏面對ajax進行註冊,註冊方式爲Ajax.Utility.RegisterTypeForAjax(typeof(命名空間.類名)),假如沒有命名空間能夠直接寫類名。代碼以下:服務器
public partial class ObjManage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage)); } }
4.2編寫cs的方法,供javascript調用。cs方法前端必需要有[Ajax.AjaxMethod],而後方法必須是公有public、靜態static。例如:異步
[Ajax.AjaxMethod] public static string getString(string str) { string strResult = "The string is " + str; return strResult; }
4.3javascript調用cs方法。調用的格式是:類名.方法名(參數),例如:測試
function alertString() { var str = ObjManage.getString("myAjax").value; alert(str); }
這樣就完成了。這個是經過測試的,假若有什麼問題,可留言。下面給出完成的源碼,對於Web.config的代碼就不給了,本身安裝第3步設置配置文件web.config進行設置就OK了。cs代碼:spa
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ObjManage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage)); } [Ajax.AjaxMethod] public static string getString(string str) { string strResult = "The string is " + str; return strResult; } }
--------------------------------------------------
aspx代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ObjManage.aspx.cs" Inherits="ObjManage" %> <!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 type="text/javascript"> function alertString() { var str = ObjManage.getString("myAjax").value; alert(str); } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="獲取信息" onclick="alertString();" /> </div> </form> </body> </html>
原文連接:http://blog.csdn.net/jony07/article/details/8080066