码迷,mamicode.com
首页 > Web开发 > 详细

ajax.js

时间:2015-08-12 21:24:59      阅读:722      评论:0      收藏:0      [点我收藏+]

标签:

一直用 都是jquery和angular的ajax库,也没看过源码,真是惭愧,一知半解,通过学习了解下

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="智能社 - zhinengshe.com" />
<meta name="copyright" content="智能社 - zhinengshe.com" />
<title>智能社 - www.zhinengshe.com</title>
<script src="myAjax5.js"></script>
<script>

window.onload = function(){
	var oBtn = document.getElementById("btn1");
	oBtn.onclick = function(){
		$.ajax({
			url:"post.php",
			data:{
				a:22,
				b:22
			},
			type:"get",
			timeout:-1,
			success:function(str){
				alert(str);
			},
			error:function(){
				alert("失败");
			}
		});
	};
};
</script>
</head>

<body>

<input id="btn1" type="button" value="按钮"/>

</body>
</html>

  

技术分享
<?php


$a = $_GET["a"];
$b = $_GET["b"];

echo $a + $b;

?>
View Code
技术分享
//版权 北京智能社©, 保留所有权利
var $ = {};
$.ajax = ajax;

function json2url(json){
    var arr = [];
    json.t = Math.random();
    for(var name in json){
        arr.push(name + "=" + encodeURIComponent(json[name]));
    }
    return arr.join("&");
}

//options url,data,type,timeout,success,error
function ajax(options){
    options = options || {};
    if(!options.url){
        alert("请输入url,别太懒了!");
        return ;
    }

    options.data = options.data || {};
    options.type = options.type || "get";
    options.timeout = options.timeout || 0;

    var str = json2url(options.data);

    //1 创建
    if(window.XMLHttpRequest){
        var xhr = new XMLHttpRequest();
    } else {
        var xhr =  new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(options.type == "get"){
        //2 连接
        xhr.open("get",options.url +"?"+str,true);
        //3 发送请求
        xhr.send();
    } else {

        //2 连接
        xhr.open("post",options.url,true);

        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        //3 发送请求
        xhr.send(str);
    }


    //4 接收数据
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){//完成
            clearTimeout(timer);
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                options.success && options.success(xhr.responseText);
            } else {
                options.error && options.error(xhr.status);
            }
        }
    };

    if(options.timeout){
        var timer = setTimeout(function(){
            xhr.abort();
        },options.timeout)
    }
}
View Code

 

ajax.js

标签:

原文地址:http://www.cnblogs.com/heboliufengjie/p/4725359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!