Home > Web Front-end > JS Tutorial > How to create ajax yourself? Detailed explanation of the steps to create ajax (with example analysis)

How to create ajax yourself? Detailed explanation of the steps to create ajax (with example analysis)

寻∝梦
Release: 2018-09-10 15:45:17
Original
3084 people have browsed it

This article mainly talks about how to create a case of ajax. Now let us take a look at this article.

I have been learning ajax for a while, now come Summarize the construction and functions of ajax.

ajax is used to request data from the background. Its characteristic is to request data asynchronously (read data without refreshing). Before ajax appears, if you fill in A form with many items is simply a nightmare for users. If any part of the form is filled in incorrectly, an error will appear during final submission, and then the form needs to be filled in again. After filling it out several times, the user will lose the ability to fill in the form. Desire. Then after the emergence of ajax, this problem was well solved. Every time an item is filled in, the result will be verified through the server and returned, which improves efficiency to a certain extent and brings a better experience to users. (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)

Now let’s explain some of the problems that exist in using ajax: First, Under IE, the data is not updated in time (caused by cache). A URL is only read once, so the URL needs to be changed every time it is refreshed. However, in the domain name? The following parameters do not affect the retrieval of the page, but browsers with different URLs will reload the page, thus solving the problem of page caching. You can pass url '?t=' new Date().getTime(); or you can use Math.random(); secondly, there is a problem with the received data format, which requires unified encoding; thirdly, ajax reads everything , all characters returned are characters, and we need to parse the data ourselves. Next, write an ajax yourself:

1. Create an ajax object var oAjax=new XMLHttpRequest() ~Higher version browser or new ActiveXObject('Microsoft. XMLHTTP')~IE

2. Establish a connection oAjax.open(mode, address, asynchronous)

3. Send request oAjax.send();

##4. Accept onreadystatechange reads when the status changes

oAjax.readyState status code

0. The ajax object has just been created (new an ajax object)

1. Connected to the server (the open method has just been executed)

2. Sending completed

3. Receiving completed (file header)

4. After the reception is completed (body), if the content request fails, there will be 4

where the http status code is:

oAjax.status 200<=n<300 or n==304 indicates successful transmission

##oAjax.responseText Return data


encodeURIComponent(str)             Strings are encoded as URI components

ajax:

##

//data 	后台要的数据
//options	=	url,data,type,timeout,success,error
function ajax(options){	
	options=options||{};
	options.data=options.data||{};
	options.type=options.type||&#39;get&#39;;
	options.timeout=options.timeout||0;	
	//整理data数据
	options.data.t=Math.random();//给data创建一个t 键
	var arr=[];
	for(var key in options.data){
		arr.push(key+&#39;=&#39;+encodeURIComponent(options.data[key]));	
	}
	var str=arr.join(&#39;&&#39;);	
	if(window.XMLHttpRequest){//1
		var oAjax=new XMLHttpRequest();	
	}else{
		var oAjax=new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);	
	}	
	if(options.type==&#39;get&#39;){
		oAjax.open(&#39;get&#39;,options.url+&#39;?&#39;+str,true);//2	
		oAjax.send();//3
	}else{//post
		oAjax.open(&#39;post&#39;,options.url,true);
			
		//设定ajax的头信息
		oAjax.setRequestHeader(&#39;Content-Type&#39;,&#39;application/x-www-form-urlencoded&#39;);		
		oAjax.send(str);		
	}
	
	oAjax.onreadystatechange=function(){//4
		if(oAjax.readyState==4){
			if(oAjax.status>=200 && oAjax.status<300 || oAjax.status==304){
				clearInterval(timer);
				options.success && options.success(oAjax.responseText)
			}else{
				options.error && options.error(oAjax.status);
			}
		}
	};
	if(options.timeout){
		var timer=setTimeout(function(){
			alert(&#39;超时了&#39;);	
			oAjax.abort();	//终止加载	
		},options.timeout);
	}	
}
Copy after login

1.

Create ajax function, Because the various parameters in ajax are uncertain and arranged in different positions, json is used as data and the parameters options are passed in. Options are optional. If passed, the passed data will be used. If not, the default will be used. Parameters, including the sending method type, timeout setting and data.

2.

The url needs to add some random variables at the end, so you can first add a key to data options.data.t=Math.random() ;Then encode the url and process the data.

3.

Then judge the browser. Both chrome and ff support window.XMLHttpRequest, while IE browser only supports ActiveXObject('Microsoft.XMLHTTP' ), and then determine the type of sending. If it is the get method, you need to add the random number just set after the url, and then you can send the data oAjax.send(); however, for the post method, you also need to set the ajax header Information oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); and then send the data

4.对状态改变时进行判断oAjax.onreadystatechange当oAjax.readyState==4时表明接收完成此时再判断状态码oAjax.status>=200 && oAjax.status<300 || oAjax.status==304时表明成功了此时进行成功时的回调函数,否则就是失败了,此时返回状态码,告诉用户。

5.在这中间可以设置一个定时器,当在设定的时间内还没有获取成功则表明超时了,此时需要终止加载oAjax.abort(),并且告诉用户超时了,如果在设置的时间内加载成功了,则清除定时器。

此时ajax就封装完毕了,调用时就简单了

ajax({
		data:	{a:3,b:5},
		url:	'php/php_get.php',
		success:function(str){
			alert(str);	
		}
	});	
Copy after login

本篇文章到这就结束了(想看更多就到PHP中文网AJAX使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How to create ajax yourself? Detailed explanation of the steps to create ajax (with example analysis). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template