Solicitud Ajax implementada por js nativo

Solicitud Ajax implementada por js nativo

1. definición de ajax
ajax = Asynchronous JavaScript And XML. Permite
ajaxla actualización asincrónica de páginas web mediante el intercambio de datos con el servidor web detrás de escena. Esto significa que se pueden actualizar partes de una página web en lugar de recargar toda la página.
(1) ¿Qué esXMLHttpRequest
XMLHttpRequest un objeto utilizado para intercambiar datos con el servidor backend? Todos los navegadores modernos ( Chrom、IE7+、Firefox、Safari以及Opera) tienen objetos integrados XMLHttpRequest. Propiedades de
Insertar descripción de la imagen aquí
(2) : XMLHttpRequest
Insertar descripción de la imagen aquí
(3) ajaxCómo funciona:
① Se produce un evento en la página web (carga de página, clic en el botón)
② El objeto XMLHttpRequest es creado por JavaScript ③
El objeto XMLHttpRequest envía una solicitud al servidor web
④ El servidor procesa la solicitud
⑤ El servidor responde con los datos enviados a la página web
⑥ Leer la respuesta por JavaScript
⑦ Realizar la acción correcta por JavaScript (como ejecutar código para actualizar la página)

2. Solicitar
(1) obtener solicitud

	<!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) Fusionar get y post y agregar llamadas de parámetros

<!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里面更改即可:

Insertar descripción de la imagen aquí

Enlace directo: https://blog.csdn.net/dkm123456/article/details/110750062

Supongo que te gusta

Origin blog.csdn.net/weixin_44021888/article/details/130873572
Recomendado
Clasificación