1. 程式人生 > >ASP.NET使用Ajax

ASP.NET使用Ajax

錯誤信息 alt bst ror sub img request ssr onf

一、新建一個html頁面,如註冊頁面"Register.htm"

<!DOCTYPE html>
<html >
<head>
    <title>用戶註冊</title>
    <meta charset="utf-8" />
    <style type="text/css">
        .msg
        {
            color:Red;
        }
    </style>
</head>
<body>
    <!-- 
        因為是ajax提交,html表單控件可以不必放在form裏,且不能使用提交按紐(type="submit"),而使用普通按紐(type="button")
    
--> 用戶名:<input type="text" name="id" id="id" /><span id="idMsg" class="msg"></span><br /> <!-- span用來顯示錯誤信息 --> 密 碼:<input type="password" name="pwd" id="pwd" /><span id="pwdMsg" class="msg"></span><br /> 姓 名:<input type="text" name="name"
id="xm" /><span id="nameMsg" class="msg"></span><br /> <input id="btnReg" type="button" value="註冊" /> <script type="text/javascript" src="bootstrap/js/jquery.js"> </script> <script src="reg.js" type="text/javascript"></script
> </body> </html>

二、新建一js文件,如:reg.js

$(function() {
    //定義清除錯誤信息的函數
    function clearMsg() {
        $(".msg").html("");
    }
    
    //定義獲取表單數據的函數,註意返回json對象
    function formData() {
        return {
            id: $("#id").val(),
            pwd: $("#pwd").val(),
            name: $("#xm").val()
        };
    }
    
    //定義註冊功能的函數
    function reg() {
        var url = "Register.ashx";
        var data = formData();
        clearMsg();
        $.ajax({
            type: ‘GET‘, //自動會把json對象轉換為查詢字符串附在url後面如:http://localhost:49521/Register.ashx?id=a&pwd=b&name=c
            url: url,
            dataType: ‘json‘, //要求服務器返回一個json類型的數據,如:{"success":true,"message":"註冊成功"}
            contentType: ‘application/json‘,//發送信息給服務器時,內容編碼的類型
            data: data, //提交給服務器的數據,直接使用json對象的數據,如:{"id":"a","pwd":"b","name":"c"} (如果要求json格式的字符串,可使用用JSON.stringify(data))
            success: function(responseData) {//如果響應成功(即200)
            if (responseData.success == true) {//responseData也是json格式,如:{"success":true,"message":"註冊成功"}
                    alert(responseData.message);
                } else {
                var msgs = responseData.msgs;//msgs對象是一個數組,如下所示:
                //{"success":false,"message":"註冊失敗","msgs":[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]}
                    for (var i = 0; i < msgs.length; i++) {
                        $(‘#‘ + msgs[i].id).html(msgs[i].message);
                    }
                }
            },
            error: function() {
            //要求為Function類型的參數,請求失敗時被調用的函數。該函數有3個參數,即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。ajax事件函數如下:
            //function(XMLHttpRequest, textStatus, errorThrown){
            //通常情況下textStatus和errorThrown只有其中一個包含信息
            //this;   //調用本次ajax請求時傳遞的options參數
                alert(arguments[1]);
            }
        });//ajax
    }
    
    //定義一個初始化函數
    function init() {
        $("#btnReg").click(function() {
            reg();
        });
    }
    
    //調用初始化函數
    init();
});

三、新建一般處理程序,如:Register.ashx

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;

namespace WebLogin
{
    /// <summary>
    /// $codebehindclassname$ 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Register1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";//設置響應內容的格式是json格式
            string id = context.Request["id"];
            string pwd = context.Request["pwd"];
            string name = context.Request["name"];
            List<string> msgList = new List<string>();
            if (String.IsNullOrEmpty(id))
            {
                msgList.Add("{\"id\":\"idMsg\",\"message\":\"用戶名不能為空.\"}");
            }
            if (pwd==null || pwd=="")
            {
                msgList.Add("{\"id\":\"pwdMsg\",\"message\":\"密碼不能為空.\"}");//形如:{"id":"pwdMsg","message":"密碼不能為空."}
            }
            if (name==null || name=="")
            {
                msgList.Add("{\"id\":\"nameMsg\",\"message\":\"姓名不能為空.\"}");
            }

            
            string responseText = "";
            if (msgList.Count == 0)
            {
                //調用後臺代碼寫入數據庫
                responseText = "{\"success\":true,\"message\":\"註冊成功\"}";
            }
            else
            {
                string msgsValue = "";
                for (int i = 0; i < msgList.Count; i++)
                {
                    msgsValue += msgList[i] + ",";//將列表中的每一個字符串連接起來,用","隔開,不過最後還會多","
                }
                msgsValue=msgsValue.Substring(0, msgsValue.Length - 1);//去掉末尾的","
                msgsValue = "[" + msgsValue + "]";//用"[]"括起來,如:[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]
                responseText = "{\"success\":false,\"message\":\"註冊失敗\",\"msgs\":" + msgsValue + "}";
                //最的形如:{"success":false,"message":"註冊失敗","msgs":[{"id":"pwdMsg","message":"密碼不能為空."},{"id":"nameMsg","message":"姓名不能為空."}]}
            }
            context.Response.Write(responseText);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

四、完成效果如圖

技術分享

ASP.NET使用Ajax