1. 程式人生 > >jquery訪問ashx文件示例

jquery訪問ashx文件示例

per user strong gin data -1 text javascrip empty

轉自原文 jquery訪問ashx文件示例

.ashx 文件用於寫web handler的。.ashx文件與.aspx文件類似,可以通過它來調用HttpHandler類,它免去了普通.aspx頁面的控件解析以及頁面處理的過程。其實就是帶HTML和C#的混合文件。

  .ashx文件適合產生供瀏覽器處理的、不需要回發處理的數據格式,例如用於生成動態圖片、動態文本等內容。很多需要用到此種處理方式。此文檔提供一個簡單的調用ashx文件的Demo,並貼出關鍵文件的源碼。

以下為Demo中Login.ashx文件中的源碼:

技術分享
public class Login : IHttpHandler {
     
    
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "application/json"; //GET方式獲取傳遞的數據 //string username = context.Request.QueryString["username"]; //string password = context.Request.QueryString["password"]; //POST方式獲取傳遞的數據 string
username = context.Request.Form["username"]; string password = context.Request.Form["password"]; string message = null; if (string.IsNullOrEmpty(username)) { message = "用戶名不能為空"; context.Response.Write("{\"success\":false,\"message\":\""
+ message + "\"}");//此JSON格式非常重要,否則會執行jquery的的error函數 context.Response.End(); } if (string.IsNullOrEmpty(password)) { message = "密碼不能為空"; context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}"); context.Response.End(); } if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { if (username.ToUpper() == "ADMIN" && password == "123") { message = "登錄成功"; context.Response.Write("{\"success\":true,\"message\":\"" + message + "\"}"); } else { message = "用戶名或密碼錯誤"; context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}"); } } context.Response.End(); } public bool IsReusable { get { return false; } } }
View Code

以下為html中的源碼:

技術分享
<title>jsquery訪問ashx文件</title>
    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script language="javascript" type="text/javascript">
        function login() {
            $.ajax({
                url: common/handler/Login.ashx,
                type: POST,
                data: { username: $("#txtUsername").val(), password: $("#txtPassword").val() },
                dataType: json,
                timeout: 50000,
                //contentType: ‘application/json;charset=utf-8‘,
                success: function (response) {                    
                    alert(response.message);
                },
                error: function (err) {
                    alert("執行失敗");                    
                }
 
            });
        }
    </script>
 
 
    <div style="width:400px; height:300px; margin:0 auto; background:#c0c0c0;">
        <dl style=" width:270px;">
            <dd><span>用戶名:</span><input style=" width:150px;" id="txtUsername" type="text"></dd>
            <dd><span>密  碼:</span><input style=" width:150px;" id="txtPassword" type="password"></dd>
            <dd><input style=" width:65px; height:23px; float:right;" onclick="login()" value="登錄" type="button"></dd>
        </dl>
     
 
 
</div>
View Code

jquery訪問ashx文件示例