Jquery Ajaxインスタンス(一)

16227 ワード

最初に簡単な例を示します.
aspxページ:

View Code
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Ajax    </title>

    <script src="http://code.jquery.com/jquery-latest.js"></script>

    <script type="text/javascript">

        $(function () {

            $("#btnAjax").click(function () {

                $.post("Ajax.ashx?action=Show", {

                    ID: "2012"

                }, function (data) {

                    var json = eval("(" + data + ")"); //    json      

                    alert(json.ID);

                });

            });

        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <input type="button" value="Ajax" id="btnAjax" />

    </div>

    </form>

</body>

</html>

 
ajax.ashx:

View Code
public class ajax : IHttpHandler

{



    public void ProcessRequest(HttpContext context)

    {

        string action = context.Request.QueryString["action"];

        switch (action)

        {

            case "Show":

                Show(); break;

        }

    }

   

    protected static void Show()

    {

        System.Threading.Thread.Sleep(3000);

        string ID = HttpContext.Current.Request["ID"];

        WriteJson("ID", ID);

    }

    /// <summary>

    ///   Json

    /// </summary>

    /// <param name="key"></param>

    /// <param name="val"></param>

    private static void WriteJson(string key, string val)

    {

        HttpContext.Current.Response.Write(GetJSON(key, val));

        HttpContext.Current.Response.ContentType = "text/plain"; //  MIME  

        HttpContext.Current.Response.End();

    }

    /// <summary>

    ///   JSON   

    /// </summary>

    /// <param name="dic"></param>

    /// <returns></returns>

    private static string GetJSON(string key, string val)

    {

        return string.Format("{{\"{0}\":\"{1}\"}}", key, val);

    }



    public bool IsReusable

    {

        get

        {

            return false;

        }

    }

 
いくつか説明があります
1 actionを取得した値に基づいて呼び出しの使用方法を決定する
2.メソッドが返す値をjson形式にフォーマットする
3当$postのコールバック関数が返すjson文字列を受け入れるには、eval解析を使用して文字列を操作する必要があります.
 
次の簡単にログインしたAjax実は、大体のコードが上の例と同じです.
aspx

View Code
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Ajax    -  </title>

    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            $("#btnLogin").click(function () {

                var name = $("#txtUserName").val();

                var pwd = $("#txtPwd").val();

                $.post("ajax.ashx?action=Login",{

                    username:name,password:pwd

                }, function (data) {

                    var json = eval("(" + data + ")");

                    if (json.status == "1") {

                        alert("    ,    ...");

                        //location.href = "";  

                    } else {

                        alert("        ");

                    }

                });



            });



        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <p><span>UserName:</span><input type="text" id="txtUserName" /></p>

    <p><span>PassWord:</span><input type="password" id="txtPwd" /></p>

    <p><input type="button" id="btnLogin" value="Ajax  " /></p>

    </div>

    </form>

</body>

</html>

ajax.ashx:

View Code
public class ajax : IHttpHandler

{



    public void ProcessRequest(HttpContext context)

    {

        string action = context.Request.QueryString["action"];

        switch (action)

        {

            case "Show":

                Show(); break;

            case "Login":

                Login();break;

        }

    }

    protected static void Login()

    {

        string strUserName = HttpContext.Current.Request["username"];

        string strPwd = HttpContext.Current.Request["password"];



        string status = string.Empty;//  

        if (strUserName == "admin" && strPwd == "123")

        {

            status = "1";

        }

        else

        {

            status = "2";

        }

        WriteJson("status", status);

    }

    protected static void Show()

    {

        string ID = HttpContext.Current.Request["ID"];

        WriteJson("ID", ID);

    }

    /// <summary>

    ///   Json

    /// </summary>

    /// <param name="key"></param>

    /// <param name="val"></param>

    private static void WriteJson(string key, string val)

    {

        HttpContext.Current.Response.Write(GetJSON(key, val));

        HttpContext.Current.Response.ContentType = "text/plain"; //  MIME  

        HttpContext.Current.Response.End();

    }

    /// <summary>

    ///   JSON   

    /// </summary>

    /// <param name="dic"></param>

    /// <returns></returns>

    private static string GetJSON(string key, string val)

    {

        return string.Format("{{\"{0}\":\"{1}\"}}", key, val);

    }



    public bool IsReusable

    {

        get

        {

            return false;

        }

    }

ajaxをよく使うときは、上のコードをカプセル化することができます.
私は簡単にajaxを書きました.jsファイル


View Code
/******************************************************************************

* filename: ajax.js

*******************************************************************************/



var imgPath = "loading.gif"; //      



var ajax = {};

//       

ajax.getPath = function (param) {

    return "ajax.ashx?action=" + param;

};



//         

ajax.loading = function (src, show) {

    show = show || false;

    //  

    if (show) {

        $(src).after("<img id=\"loading\" src='" + imgPath + "' title='   ...' alt='   ...' />");

        //$(src).hide();

    } else {

        //  

        // $(src).show();

        $("#loading").hide();

        $(src).next().hide();

    }

};





var Tool = {};

//  JSON  

Tool.getJSON = function (str) {

    if (str == null || str == "") {

        return [];

    }

    return eval("(" + str + ")");

};

aspxページ:


View Code
<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>    </title>

    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

    <script type="text/javascript" src="ajax.js"></script>

    <script type="text/javascript">

        $(function () {

            $("#AjaxTest").click(function () {

                ajax.loading(this, true);

                $.post(ajax.getPath("Show"), {

                    ID: "2"

                }, function (data) {

                    ajax.loading(this, false);

                    var json = Tool.getJSON(data);

                    alert(json.ID);

                    

                });

            });

        });

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <input type="button" value="AjaxTest" id="AjaxTest" /><!--<img id="loading" src=loading.gif title='   ...' alt='   ...' />-->

    </div>

    </form>

</body>

</html>

ajaxも含まれています.ashxファイル
簡単に登録した例は、それによって修正することもできます.