This article mainly introduces how to use native js to implement Ajax. It has certain reference value. Now I share it with you. Friends in need can refer to it
Create Ajax Object
Connect to server
-
Send request
1 | - `send()`接受一个参数(作为请求主体发送的数据),如果没有数据则必须传入`null`,因为这个参数对有些浏览器来说是必须的。调用`send()`之后,请求就会被分配到服务器
|
Copy after login
-
Receive return
1 2 3 4 5 6 7 8 9 10 11 12 | - 客户端和服务器端有交互的时候会调用`onreadystatechange`
- oAjax.`readyState` **表示请求/响应过程的当前活动阶段**。
- 0->(未初始化):还没有调用 `open()` 方法。
- 1->(载入):已调用 `send()` 方法,正在发送请求。
- 2->载入完成):`send()` 方法完成,已收到全部响应内容。
- 3->(解析):正在解析响应内容。
- 4->(完成):响应内容解析完成,可以在客户端调用。
- `responseText`:作为响应主体被返回的文本;
- `responseXML`:若响应的内容类型是` "text/xml" `或` "application/xml" `,该属性中将保存着包含着响应数据的`XML DOM`文档
- `status`:响应的`HTTP`状态;
- `statusText`:`HTTP`状态的说明;
|
Copy after login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function ajax(url, fnSucc){
if (window.XMLHttpRequest){
var XHR = new XMLHTTPRequest();
} else {
var XHR = new ActiveXObject( "Microsoft.XMLHTTP" );
}
XHR.onreadystatechange = function (){
if (XHR.readyState == 4){
if (XHR.status >= 200 && XHR.status <= 300 || XHR.status == 304){
fnSucc(XHR.responseText);
} else {
if (fnFiled){
fnFiled(XHR.status);
}
}
}
}
XHR.open( "GET" , url, true);
XHR.send(null);
}
|
Copy after login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function createXHR(){
if (typeof XMLHttpRequest != "undefined" ){
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined" ){
if (typeof arguments.callee.activeXString != "string" ){
var versions = [ "MSXML2.XMLHttp.6.0" , "MSXML2.XMLHttp.3.0" , "MSXML2.XMLHttp" ],
i, len = versions.length;
for (i = 0; i < len; i++){
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
berak;
}
}
} else {
throw new Error( "No XHR object available." )
}
}
|
Copy after login
1 2 3 4 5 6 7 8 | window.onload = function (){
var btn = document.getElementById( "btn1" );
btn.onclick = function (){
ajax( 'a.txt' , function fnSucc(str){
alert(str)
});
}
}
|
Copy after login
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Analysis of Sizzle, the selector engine in jQuery
Introduction to how Ajax implements cross-domain access
The above is the detailed content of How to use native js to implement Ajax. For more information, please follow other related articles on the PHP Chinese website!