原生js实现的ajax请求

原生js实现的ajax请求

1. ajax定义
ajax = Asynchronous JavaScript And XML.
ajax允许通过与场景后的Web服务器交换数据来异步更新网页。这意味着可以更新网页的部分,而不是重新加载整个页面。
(1)什么是XMLHttpRequest
XMLHttpRequest对象用于同后台服务器交换数据;所有现代浏览器(Chrom、IE7+、Firefox、Safari以及Opera)都有内建的XMLHttpRequest对象。
在这里插入图片描述
(2)XMLHttpRequest的属性:
在这里插入图片描述
(3)ajax如何工作:
① 网页中发生一个事件(页面加载、按钮点击)
②由JavaScript创建XMLHttpRequest对象
③XMLHttpRequest对象向web服务器发送请求
④服务器处理请求
⑤服务器响应数据发送会网页
⑥由JavaScript读取响应
⑦由JavaScript执行正确的动作(比如执行代码更新页面)

2. 请求
(1)get请求

	<!DOCTYPE html>
	<html>
	    <head>
	        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
	        </head>
	        <body>
	        
	        <p id="txt"></p>
	        <button onclick="do_get()">获取数据</button>
	        </body>
	<script>
	 
	function getXhr(){
		if (window.XMLHttpRequest) {
		    // 用于现代浏览器的代码
		     xmlhttp = new XMLHttpRequest();
		 } else {
		    // 应对老版本 IE 浏览器的代码
		     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		 }
		 return xmlhttp;
	}
	 
	function get(url,async){
		var xhr = getXhr();
			xhr.open('GET',url,async);
			xhr.send(null);
			xhr.onreadystatechange=function(){
				if(xhr.readyState ===4){
					var text ;
					if(xhr.status === 200){
						text=xhr.responseText;
					}else{
						text='获取失败';
					}
					callback(text);
				}
			}
	}
	 
	function callback(text){
		document.getElementById("txt").innerText=text;
	}
	 
	function do_get(){
		get("ajax_test.txt",true);
	}	
	</script>
	</html>
	```
(2)post请求
```javascript
	<!DOCTYPE html>
	<html>
	    <head>
	        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
	        </head>
	        <body>
	        
	        <p id="txt"></p>
	        <button onclick="do_post()">获取数据</button>
	        </body>
	<script>
	 
	function getXhr(){
		if (window.XMLHttpRequest) {
		    // 用于现代浏览器的代码
		     xmlhttp = new XMLHttpRequest();
		 } else {
		    // 应对老版本 IE 浏览器的代码
		     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		 }
		 return xmlhttp;
	}
	 
	function get(url,async){
		var xhr = getXhr();
			xhr.open('GET',url,async);
			xhr.send(null);
			xhr.onreadystatechange=function(){
				if(xhr.readyState ===4){
					var text ;
					if(xhr.status === 200){
						text=xhr.responseText;
					}else{
						text='获取失败';
					}
					callback(text);
				}
			}
	}
	 
	function post(url,async){
		var xhr = getXhr();
			xhr.open('POST',url,async);
			//post需加上这句,不然报错
			xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			xhr.send();
			xhr.onreadystatechange=function(){
				if(xhr.readyState ===4){
					var text ;
					if(xhr.status === 200){
						text=xhr.responseText;
					}else{
						text='获取失败';
					}
					callback("POST "+text);
				}
			}
	}
	 
	function callback(text){
		document.getElementById("txt").innerText=text;
	}
	 
	function do_get(){
		get("ajax_test.txt",true);
	}	
	function do_post(){
		post("ajax_test.txt",true);
	}
	</script>
	</html>

(3)get、post合并,并加上参数的调用

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=GBK">
        </head>
        <body>
        
        <p id="txt"></p>
        <button onclick="do_ajax()">获取数据</button>
        </body>
<script>
	function _doAjax(option){
		var xhr = window.XMLHttpRequest ? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
		if(!xhr){
			throw new Error('不支持发起http请求!');
		}
		var opt = option || {},
			url = opt.url,
			async = opt.async ,
			type = (opt.type || 'GET').toUpperCase(),
			data = opt.data || {};
			
			if(typeof async === 'undefined'){
				async = true ;//如果跨域,这个参数用false不行
			}
			if(!url){
				throw new Error('请填写url!');
			}
			xhr.open(type,url,async);
			type === 'POST' && xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			xhr.send(type === 'GET'?null : formatData(data));
			xhr.onreadystatechange=function(){
				if(xhr.readyState ===4){
					if(xhr.status === 200){
						cb(type+" "+xhr.responseText,'suc');
					}else{
						cb(type+" "+xhr.responseText,'fail');
					}
				}
			}
				
		function formatData(data){
			var rData='';
			for(var key in data){
				rData += key + '=' + data[key] + '&';
			}
			return rData.replace(/&$/,'');
		}
	}
	
	function cb(text,result){
		document.getElementById("txt").innerText=text;
	}
	
	function do_ajax(){
		var option = {
			url:'ajax_test.txt',
			type:'get',
			async:true,
			data:{}
		}
		_doAjax(option);
	}
	
	
</script>
</html>
若需要修改调用的方式或者传入的参数 ,只需要在option里面更改即可

在这里插入图片描述

转发链接:https://blog.csdn.net/dkm123456/article/details/110750062

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值