封装ajax

如果你了解了js面向对象,HTTP协议,那么就自己动手写一个AJAX框架就可以了。小技术,大家不要笑啊!

源码:(注释就不写了,应该不难看懂的)

var ajax = {
    _params: null,
    _callback: null,
    _xhr: null,

   _createXHR: function () {
        if (window.ActiveXObject) {
            _xhr = new ActiveXObject("Microsoft.XMLHTTP");     //IE
        }
        else if (window.XMLHttpRequest) {
            _xhr = new XMLHttpRequest();      //FireFox,Chrome et.
        }
    },

   _ajaxcallback: function () {
        if (_xhr.readyState == 4) {
            if (_xhr.status == 200) {
                _callback.call(this, _xhr.responseText)
            }
        }
    },

   _changeParams: function () {
        var args = arguments[0];
        var s = "";
        for (var i in args) {
            s += "&" + i + "=" + args[i];
        }
        _params = s;
    },

   get: function (url, params, callback) {
        _callback = callback;
        ajax._createXHR();
        ajax._changeParams(params);
        if (null != _xhr) {
            _xhr.open('get', url + '?' + _params, true);
            _xhr.onreadystatechange = ajax._ajaxcallback;
            _xhr.send();
        }
    },

   post: function (url, params, callback) {
        _callback = callback;
        ajax._createXHR();
        ajax._changeParams(params);
        if (null != _xhr) {
            _xhr.open('post', url, true);
            _xhr.onreadystatechange = ajax._ajaxcallback;
            _xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            _xhr.send(_params);
        }
    }
}

使用就很简单了。

1.先插入引用。

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

 

2.然后写 js代码:(ajaxtest.htm)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="js/ajax.js" type="text/javascript"></script>
    <script type="text/javascript">
        function ajaxtest() {
            var uid = document.getElementByIdx_x("txtuid").value;
            var pwd = document.getElementByIdx_x("txtpwd").value;
            ajax.get("ajaxtest.ashx", { "uid": uid, "pwd": pwd }, function (data) {
                alert(data);
            });
        }
    </script>
</head>
<body>
<input type="text" id="txtuid" />
<input type="text" id="txtpwd" onblur="ajaxtest()"/>
</body>
</html>


3.用C#建一个一般处理程序:(ajaxtest.ashx)

<%@ WebHandler Language="C#" class="ajaxtest" %>

using System;
using System.Web;

public class ajaxtest : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        var uid = context.Request["uid"];
        var pwd = context.Request["pwd"];
        context.Response.Write( uid +":" +pwd);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

这里的框架使用就和JQuery里一样,不过要注意参数的顺序:

 

ajax.get(

posted @ 2012-02-09 13:40  有梦就能实现  阅读(347)  评论(0编辑  收藏  举报