Ajax 简单封装

 1 //原生Ajax 代码:
 2 
 3  var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); //创建XMLHTTP对象,考虑兼容性
 4             xmlhttp.open("POST", "AJAXTest.ashx?" + "i=5", true); //“准备”向服务器的AJAXTest.ashx发出Post请求(GET可能会有缓存问题)。这里还没有发出请求
 5             xmlhttp.onreadystatechange = function ()
 6             {
           
封装后的 Ajax.js
function ajax(url, onsuccess)
{
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new     ActiveXObject('Microsoft.XMLHTTP');
            xmlhttp.open("POST", url, true);
            xmlhttp.onreadystatechange = function ()
            {
                if (xmlhttp.readyState == 4)
                {
                    if (xmlhttp.status == 200)
                    {
                        onsuccess(xmlhttp.responseText);
                    }
                }
            }
            xmlhttp.send(); //这时才开始发送请求
}

 

//readyState == 4 表示服务器返回完成数据了。之前可能会经历2(请求已发送,正在处理中)、3 正在交互(响应中已有部分数据可用了,但是服务器还没有完成响应的生成)2 已读取 1 读取中 0 未初始化       
 7                 if (xmlhttp.readyState == 4) 
 8                 {
 9                     if (xmlhttp.status == 200) //如果状态码为200则是成功
10                     {
11                         alert(xmlhttp.responseText);
12                     }
13                     else
14                     {
15                         alert("AJAX服务器返回错误!");
16                     }
17                 }
18             }
19 //不要以为if (xmlhttp.readyState == 4) {在send之前执行!!!!
20             xmlhttp.send(); //这时才开始发送请求

页面上调用时,引入 ajax.js 文件

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

1 function refreshCount()
2 {
3     ajax("提交到处理文件路径", function(resultText) {
4         // 业务处理
5     })
6 }
View Code

 

posted @ 2015-05-19 00:35  wqsky  阅读(171)  评论(0编辑  收藏  举报