jQuery 的 $.ajax() 可以搭配多種後端形式。這裡整理三種常見組合,方便依專案狀況挑選。
前台 JS 程式碼:
. 程式碼如下:
$("#Button1").bind("click", function () {
$.ajax({
type: "post",
url: "default.aspx",
data: "name=" + $("#Text1").val(),
success: function (result) {
alert(result.msg);
}
});
});
. 程式碼如下:
<input id="Text1" type="text" value='張三'/>
<input id="Button1" type="button" value="提交" />
後台 C# 程式碼:
. 程式碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (Request["name"]!=null)
{
Response.ContentType = "text/json";
Response.Write("{\"msg\":\""+Request["name"]+"\"}");// 把資料拼成 JSON
Response.End();
}
}
. 程式碼如下:
$("#Button2").bind("click", function () {
$.ajax({
type: "post",
contentType: "application/json",
url: "WebService.asmx/HelloWorld",
data: "{name:'" + $("#Text1").val() + "'}",
datatype: "json",
success: function (result) {
alert(result.d);
}
});
});
<input id="Button2" type="button" value="向 WebService 提交" />
WebService 程式碼:
. 程式碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要讓此 Web Service 能被指令碼呼叫(使用 ASP.NET AJAX),請取消下一行的註解。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
// 若使用設計的元件,請取消下一行的註解
//InitializeComponent();
}
[WebMethod]
public string HelloWorld( string name) {
return "Hello World"+name;
}
}
要點是必須加上 ScriptService 標籤,且回傳值會被包在屬性 d 裡,所以前端要取 result.d。
寫法與 aspx 幾乎相同,只是少了 Page 生命週期的負擔,效能通常更好。
JS 程式碼:
. 程式碼如下:
$("#Button3").bind("click", function () {
$.ajax({
type: "post",
url: "Handler.ashx",
data: "name=" + $("#Text1").val(),
success: function (result) {
alert(result.msg);
}
});
});
後台程式碼:
. 程式碼如下:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/json";
context.Response.Write("{\"msg\":\"Hello World"+context.Request["name"]+"來自 handler.ashx\"}");
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
三種方式中,如果只是要回傳資料而不需要 ASP.NET 表單機制,ashx 通常是最乾淨的選擇。