1. 程式人生 > >ASP.NET -- 一般處理程式ashx

ASP.NET -- 一般處理程式ashx

ASP.NET  --   一般處理程式ashx

如果在一個html頁面向伺服器端請求資料,可用ashx作為後臺頁面處理資料。ashx適合用作資料後臺處理,相當於WebForm中的aspx.cs檔案或aspx.vb檔案。

入門案例:html頁面向ashx頁面請求資料,ashx作為後臺頁面返回資料。

前端html頁面:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<
title>My Test ashx</title> <script type="text/javascript" src="./js/jquery-2.0.3.min.js" ></script> <script type="text/javascript" > $(function() { $("#btn_Test").click(function() { $.ajax({ type: "post", url:
"Test.ashx", datatype: "text", data: { "TestAction":"getBaiduUrl"}, success: function(data) { $("#myDiv1").html(data); } }); }); }); </script> </head>
<body> <button type="button" id="btn_Test">Test</button> <div id="myDiv1" style="width:300px;height:30px;padding: 10px;border:2px solid blue;"> </div> </body> </html>

 

後臺Test.ashx頁面:

<%@ WebHandler Language="C#" Class="Test" %>

using System;
using System.Web;

public class Test : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        if (context.Request["TestAction"] == "getBaiduUrl")
        {
            context.Response.Write("百度的地址是: https://www.baidu.com");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

執行結果: