var http = null;
复制代码
http = new XMLHttpRequest();
复制代码
open方法有三个参数,分别是javascript
http.open('GET' , '/api/test.php?name=wang' , true);
复制代码
若是为POST提交的话,那么须要设置请求头部,在把参数设置在sen();中php
http.open('POST','/api/test.php',true)
http.setRequestHeder(xxxxx格式);
http.send('name=wang');
复制代码
http.send();
复制代码
提交请求后,咱们能够经过onreadystatechage去监测响应,看下是否成功,readyState一共有五个状态,到达4的时候说明相应内容已经解完成了,也能够经过XMLHttpRequest.onload来代替,当等于4时,经过status获取状态码。java
http.onload = function (){
if(http.status === 200){
console.log('ajax yes!');
}else{
console.log('ajax no!')
}
}
复制代码
状态码 | 信息 |
---|---|
200 | 表示响应结果请求被正常处理了 |
204 | 表示请求资源成功,可是没有资源能够返回 |
206 | 表示请求资源的某一部分,响应中包含content-range |
301 | 表示资源的访问路径(URL)被变动 |
302 | 表示请求的资源已经在其余位置了,可是默认你已经知道了 |
303 | 表示请求的资源已经在其余位置了,应使用 GET 方法定向获取请求的资源。 |
304 | 表示资源已经请求到到了,可是未能按照正常的方式请求 |
307 | 临时重定向。 |
400 | 请求报文中存在语法错误,须要修改请求内容从新请求 |
401 | 须要经过http认证,若以前已进行过 1 次请求,则表示用 户认证失败 |
403 | 服务器拒绝你的的访问 |
404 | 服务器上没有请求的资源,多是地址写错了....... |
405 | 客户端的请求方法被服务器禁止 |
500 | 服务器资源发生了错误 |
503 | 服务器没法请求 |
总结 | 2xx为请求成功,3xx为URL被改变了,4xx客户端错误,5xx服务器错误 |
/** /** * ajax封装,参数传递一个对象 * url : 请求地址 * type : 请求方式 * dataType : 请求值返回值 * data : 参数对象 * async : 异步 * success : function 成功函数 => 参数是响应内容 * error : function 异常函数 => 参数内容是响应码 **/
var ajax = function (obj) {
//默认传入一个对象,若是没有,就为空对象
obj = obj || {};
//默认GET请求
obj.type = (obj.type || 'GET').toUpperCase();
//默认返回JSON数据
obj.dataType = obj.dataType || 'JSON';
//默认异步请求
obj.async = obj.async || true;
//参数处理,执行getParams方法
var data = getParams(obj.data);
var http;
/** * 建立AJAX的实例适配 * W3C使用XMLHttpRequest * IE使用ActiveXObject('Microsoft.XMLHTTP'); * */
if (window.XMLHttpRequest){
//w3c
http = new XMLHttpRequest();
}else {
//IE
http = new ActiveXObject('Microsoft.XMLHTTP');
}
/** * 请求方式的封装 * GET和POST请求 * */
if (obj.type === 'GET'){
http.open("GET",obj.url+'?'+data,obj.async);
http.send();
}else if (obj.type === 'POST'){
http.open('POST',obj.url,obj.async);
//设置头部参数
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//提交post数据
http.send(data);
}
/** * 监听响应接口 * 若是步骤4的请求状态码为正确的就执行success函数 * 若是错误的话就执行error函数 * */
http.onreadystatechange = function () {
if (http.readyState === 4){
//若是响应内容完成了,判断状态码
var status = http.status;
if (status >= 200 && status < 300){
//回调
obj.success && obj.success(http.responseText,http.responseXML);
} else {
obj.error && obj.error(status);
}
}
};
};
/** * 对象参数的处理 * 转换成为须要的字符串 */
function getParams(data) {
var arr = [];
for (var param in data){
arr.push(encodeURIComponent(param) + '=' +encodeURIComponent(data[param]));
}
console.log(arr);
arr.push(('randomNumber=' + Math.random()).replace('.'));
return arr.join('&');
}
复制代码
jQuery封装的ajax的使用 GETjquery
$.ajax({
type:'get',
url: "url",
data:{'foo':'bar'},
success: function(res) {
load_content(res);
}
});
复制代码
POSTajax
$.ajax({
url: "url",
success: function(res) {
//设置到页面上
console.log(typeof res);
}
});
复制代码
jquery的ajax原理也相对差很少,它给开发者处理了很是多的兼容性问题,大大优化了开发者在写ajax形成的代码重复。。。。。。。。。。api