The main feature of AJax is to use scripts to manipulate data exchange between HTTP and web servers without causing page reloading.
Using XMLHttpRequest
All modern browsers support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject).
Create XMLHttpRequest object
var xmlhttp =new XMLHttpRequest()
var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
For example
function createXML(){
if(typeof XMLHttpRequest != "undefined"){//标准
return new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){//兼容IE5,IE6
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len;
for (i=0,len=versions.length; i < len; i++) {
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
}catch(ex){ //跳过
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("no XRL object available.");
}
}var xml = new createXML();
Copy after login
Specify request
After the object is created, the next step to initiate an http request is to call the open() method of the XMLHttpRequest object. It receives three parameters:
The type of request to send, case-insensitive
The requested URL, here relative to the document URL, if the absolute URL, protocol, host and port are specified, they must match the corresponding content of the document: cross-domain requests will usually report an error
Boolean value of whether to send asynchronously; If there is request header, then the next step is to set it.
If the request header is called multiple times, overwriting will not occur
If the request requires a password-protected URL, the username and The password is passed as the fourth and fifth parameters to open()
The last step in making the request is to specify the optional body and send it to the server. It should be noted that GET requests have absolutely no body, but when using POST to send a request, you must cooperate with the setRequestHeader method
xml.send(null);
Copy after login
Get a response
A complete HTTP response has a status code, response It consists of a collection of headers and a response body. These are available through the properties and methods of the XMLHttpRequest object:
- The status and statusText properties return the HTTP status code (such as 200 ok) in the form of numbers and text
- Use getResponseHeader and getAllResponseHeaders() to query response headers
- The response body can be obtained in text form from the responseText attribute and in Document form from the responseXML attribute
- XMLHttpRequest objects are typically used asynchronously: the send method returns immediately after sending the request, and the response methods and properties listed previously are not valid until the response returns. In order to be notified when the response is ready, you must listen to the readystatechange event on the XMLHttp object
readyState is an integer that specifies the status of the HTTP request
For example
var xml = new createXML();xml.open("get","hello-world.html",false);xml.onreadystatechange = function(url,callback){ if(xml.readyState === 4){ if((xml.status >= 200 && xml.status < 300) || xml.status === 304){
console.log(xml.responseText);
}else{
console.log("request is not ok" + xml.status);
}
}
}xml.send(null);
function encodeFormData(data){
if(!data) return "";//无数据就返回空串
var pairs = [];//用来保存键值对
for(var name in data){ if(!data.hasOwnProperty(name)) continue;//跳过继承属性
if(typeof data[name] === "function") continue;//跳过方法
var value = data[name].toString();
name = encodeURIComponent(name.replace(/%20/g,"+"))//因为由于历史原因,表单提交的 x-www-form-urlencoded 格式要求空格编码为 + 。但 encodeURIComponent 是遵照后来的标准编码为 %20 的。
value = encodeURIComponent(value.replace(/%20/g,"+"))
pairs.push(name + "=" + value);
} return paris.join('&')//连接键值对}function getData(url,data,callback){
var request = new XMLHttpRequest()
request.open("GET",url+"?"+encodeFormData(data))
request.onreadystatechange = function(){
if(request.readyState === 4 && callback) callback(request)
}
request.send(null);
}function postData(url,data,callback){
var request = new XMLHttpRequest();
request.open("POST",url);
request.onreadystatechange = function(){
if(request.readyState === 4 && callback){
callback(request);
}
}
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(encodeURIComponent(data));
}
Copy after login
JSON编码的请求
举个栗子
function postJson(url,data,callback){
var request = new XMLHttpRequest();
request.open("POST",url);
request.onreadystatechange = function(){
if(request.readyState === 4 && callback){
callback(request);
}
} request.setRequestHeader("Content-Type","application/json");
request.send(JSON.stringify(data));
}
Copy after login
上传文件
举个栗子
input.addEventListener("change",function(){//添加事件监听
var file = this.file[0];
var xhr = new XMLHttpRequest();
xhr.open("POST",URL);
xhr.send(file);
},false)
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