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

一个简单ajax实现方式

时间:2016-11-30 14:02:45      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:javascrip   state   header   简单   ons   nstat   set   index   title   

http://www.cnblogs.com/rubylouvre/archive/2013/01/08/2851051.html

  

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script>
		Ajax = function(){
		    function request(url,opt){
		        function fn(){}
		        var async   = opt.async !== false,
		            method  = opt.method    || ‘GET‘,
		            data    = opt.data      || null,
		            success = opt.success   || fn,
		            failure = opt.failure   || fn;
		            method  = method.toUpperCase();
		        if(method == ‘GET‘ && data){
		            url += (url.indexOf(‘?‘) == -1 ? ‘?‘ : ‘&‘) + data;
		            data = null;
		        }
		        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(‘Microsoft.XMLHTTP‘);
		        xhr.onreadystatechange = function(){
		            _onStateChange(xhr,success,failure);
		        };
		        xhr.open(method,url,async);
		        if(method == ‘POST‘){
		            xhr.setRequestHeader(‘Content-type‘, ‘application/x-www-form-urlencoded;‘);
		        }
		        xhr.send(data);
		        return xhr; 
		    }
		    function _onStateChange(xhr,success,failure){
		        if(xhr.readyState == 4){
		            var s = xhr.status;
		            if(s>= 200 && s < 300){
		                success(xhr);
		            }else{
		                failure(xhr);
		            }
		        }else{}
		    }
		    return {request:request};   
		}();

		console.log(Ajax.request("http://baidu.com",{method:"POST"}));
	</script>
</body>
</html>

  

一个简单ajax实现方式

标签:javascrip   state   header   简单   ons   nstat   set   index   title   

原文地址:http://www.cnblogs.com/zhujiasheng/p/6117067.html

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