寫一個 Handler 的程式,其副檔名為 ashx.
先開一個新的 GetData.ashx 檔案.
GetData.ashx
<%@ WebHandler Language="C#" Class="GetData" %>
using System.Web;
using System.Data;
public class GetData : IHttpHandler {
public void ProcessRequest (HttpContext context) {
prj_class my_class = new prj_class();
int id = int.Parse(context.Request["id"]);
DataTable dt = my_class.GetData(id);
string result = "[";
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
result += string.Format("{{\"Id\":\"{0}\" ,\" Name\":\"{1}\"}},",
row["Id"].ToString(),
row["Name"].ToString()
);
}
result = result.TrimEnd(',');
}
result += "]";
context.Response.Write(result);
}
public bool IsReusable {
get {
return false;
}
}
}
前端ajax:
var techdata=null;
var ChkTechData=false;
$.ajax({
url: "GetData.ashx",
type: 'get',
data: { id: "25" }, //若有多個參數用逗號,例如id:"25",name:"david"
async: false,
dataType: 'json',
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
success: function (response) {
techdata = response;
if(techdata.length >0){
ChkTechData=true;
}
}
});
留言列表