Home  >  Article  >  Web Front-end  >  Introduction to several methods of implementing native ajax in javascript_javascript skills

Introduction to several methods of implementing native ajax in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:22:101094browse

Since JavaScript has various frameworks, such as jquery, using ajax has become quite simple. But sometimes in order to pursue simplicity, there may be no need to load a huge js plug-in like jquery in the project. But what should I do if I want to use ajax function? Let me share with you several ways to use javascript to implement native ajax.

You must create an XMLHttpRequest object before implementing ajax. If the browser that created the object does not support it, you need to create an ActiveXObject. The specific method is as follows:

Copy the code The code is as follows:

var xmlHttp;
function createxmlHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if ( window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
}

(1) The following uses the xmlHttp created above to implement the simplest ajax get request:
Copy code The code is as follows:

function doGet(url){
// Pay attention to the parameter value passed in It is best to use encodeURI to handle it to prevent garbled characters
createxmlHttpRequest();
xmlHttp.open("GET",url);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
alert('success');
} else {
alert(' fail');
}
}
}

(2) Use the xmlHttp created above to implement the simplest ajax post request:
Copy code The code is as follows:

function doPost(url,data){
// Be careful when passing parameter values. It is best to use encodeURI to handle it to prevent garbled characters
createxmlHttpRequest();
xmlHttp.open("POST",url);
xmlHttp.setRequestHeader("Content-Type","application/x-www -form-urlencoded");
xmlHttp.send(data);
xmlHttp.onreadystatechange = function() {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) ) {
alert('success');
} else {
alert('fail');
}
}
}
Statement:
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