雖然aspx現在用的越來越少,但是以前的一些項目仍舊是使用WebForm來實現的,我們仍然會遇到使用WebForm 並且實現AJAX的需求:
現在提供兩種方法來實現aspx頁面通過ajax調用aspx后台的方法。
1 是 引用webservrice 並且使用靜態方法
后台代碼:
using System.Web.Services; //WebMethod 依賴於此引用 [WebMethod] public static int Add(int num1, int num2) { return num1 + num2; }
前台調用:
<script src="Scripts/jquery-1.10.2.min.js"></script> //引入jquery function add(a, b) { $.ajax({ url: "WebFprmAjax.aspx/Add", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify({ num1: a, num2: b }), success: function (data) { alert(data.d) } }) }
2 是 手工輸出請求流的形式
后台代碼:
protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(this.Request.Form["type"]) && (this.Request.Form["type"] == "ajax")) { this.DoCallback(); } } //根據不同的action 確認需要調用的是哪一個方法,並輸出返回結果 private void DoCallback() { string action = this.Request.Form["Action"]; this.Response.Clear(); this.Response.ContentType = "application/json"; string writeText = string.Empty; switch (action) { case "Subtraction": writeText = Subtraction(); break; } this.Response.Write(writeText); this.Response.End(); } //實際負責計算的方法 private string Subtraction() { int a = int.Parse(this.Request.Form["num1"]); int b = int.Parse(this.Request.Form["num1"]); var result = new { statue = true, msg = a + b }; //使用Newtonsoft來序列化一個匿名對象,從而實現轉化為json返回格式 return Newtonsoft.Json.JsonConvert.SerializeObject(result); }
前台調用:
function sub(a,b) { $.ajax({ url: "WebFprmAjax.aspx?v=" + new Date().getTime(), //防止被瀏覽器緩存 type: 'POST', dataType: 'json', timeout: 10000, data: {
Action: "Subtraction", //調用方法名 type: "ajax", //自定義標識判斷ajax方法 num1: a, num2: b //提交的數據 } , //contentType: "application/json; charset=utf-8", //不能使用接送 會造成request.form 無法獲取到對應參數 success: function (data) { if (data.statue) { alert(data.msg) } else { alert("系統忙請稍后再試!"); } } }); }
以上是在webForm頁面ajax調用自身后台頁面的兩種方式,各有其優點,當然ajax調用后台遠遠不止這兩種方式,還有更多的歡迎分享