简版GET请求
同步请求
const type = 'GET';
const url = '/api/login?name=test&&pswd=123';
const isAsync = false;
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.send(null);
if (xhr.status == 200) {
console.log(xhr.responseText); //成功结果
} else {
console.log(xhr.response); //失败结果
}
异步请求
const type = 'GET';
const url = '/api/login?name=test&&pswd=123';
const isAsync = true;
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText); //成功结果
} else {
console.log(xhr.response); //失败结果
}
}
};
简版PSOT请求
同步请求
const type = 'POST';
const url = '/api/login';
const isAsync = false;
const data = { name: 'test', pswd: '123' };
const xhr = new XMLHttpRequest();
xhr.open(type, url , isAsync);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
if (xhr.status == 200) {
console.log(xhr.responseText); //成功结果
} else {
console.log(xhr.response); //失败结果
}
异步请求
const type = 'POST';
const url = '/api/login';
const isAsync = false;
const data = { name: 'test', pswd: '123' };
const xhr = new XMLHttpRequest();
xhr.open(type, url, isAsync);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText); //成功结果
} else {
console.log(xhr.response); //失败结果
}
}
};
服务器端响应结果XHR 对象属性说明
属性名 | 说明 |
---|---|
responseText | 作为响应主体被返回的文本 |
responseXML | 如果响应主体内容类型是"text/xml"或"application/xml", 则返回包含响应数据的 XMLDOM 文档 |
status | 响应的 HTTP 状态 |
statusText | HTTP 状态的说明 |
异步调用触发 readystatechange事件readyState 属性说明
值 | 状态 | 说明 |
---|---|---|
0 | 未初始化 | 尚未调用 open()方法 |
1 | 启动 | 已经调用 open()方法,但尚未调用 send()方法 |
2 | 发送 | 已经调用 send()方法,但尚未接受响应 |
3 | 接收 | 已经接收到部分响应数据 |
4 | 完成 | 已经接收到全部响应数据,而且可以使用 |
HTTP状态码
HTTP 状态码 | 状态字符串 | 说明 |
---|---|---|
200 | OK | 服务器成功返回了页面 |
400 | BadRequest | 语法错误导致服务器不识别 |
401 | Unauthorized | 请求需要用户认证 |
404 | Notfound | 指定的 URL 在服务器上找不到 |
500 | InternalServer Error | 服务器遇到意外错误,无法完成请求 |
503 | ServiceUnavailable | 由于服务器过载或维护导致无法完成请求 |
封装ajax方法一
function ajax(obj){
var xhr = createXHR();
obj.method = obj.method || 'get'; //默认以get方式发送
obj.async = obj.async || true; //默认为异步请求
obj.url += '?rang='+ Math.random();
obj.data = params(obj.data);
if(obj.method === 'get'){
obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data;
}
if(obj.async === true){
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
callback();
}
}
}
xhr.open(obj.method,obj.url,obj.async);
if(obj.method === 'post'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(obj.data);
}else{
xhr.send(null);
}
if(obj.async === false){
callback();
}
function callback(){
if(xhr.status == 200){
obj.success(xhr.responseText);
}else{
obj.error(xhr);
}
}
function createXHR(){
if(typeof XMLHttpRequest != 'undefined'){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
var version = [
'MSXML2.XMLHttp.6.0',
'MSXML2.XMLHttp.3.0',
'MSXML2.XMLHttp'
];
for(var i=0; i<version.length; i++){
try{
return new ActiveXObject(version[i]);
}catch(e){
//跳过
}
}
}else{
throw new Error('您的系统或浏览器不支持XHR');
}
}
function params(data){
var arr = [];
for(var i in data){
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}
}
//调用ajax
addEvent(document,'click',function(){
ajax({
url: 'demo.php',
data: {
name: 'Le&e',
age: 100
},
success: function(text){
alert(text);
},
error: function(xhr){
alert('获取数据错误,错误代号:' + xhr.status + '错误信息:' + xhr.statusText);
}
});
})
//demo.php
<?php
header('charset=utf-8');
//echo Date('Y-m-d H:i:s');
print_r($_GET);
/*if($_GET['name'] == 'Lee'){
echo '李合飞';
}*/
print_r($_POST);
/*if($_POST['name'] == 'Lee'){
echo '李合飞';
}*/
?>
封装ajax方法二
function ajax(obj){
obj.type = obj.type || 'get';
obj.async = obj.async || true;
obj.url += '?t=' + new Date().getTime();
obj.data = params(obj.data);
if(obj.type === 'get'){
obj.url += obj.url.indexOf('?') == -1 ? '?' + obj.data : '&' + obj.data;
}
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open(obj.type, obj.url, obj.async);
if(obj.type === 'get'){
xhr.send(null);
}else{
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(obj.data);
}
if(obj.async === true){
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
callback();
}
};
}else{
callback();
}
function callback(){
if(xhr.status == 200){
obj.success(xhr.responseText);
}else{
if(obj.error){
obj.error(xhr.response);
}
}
}
function params(data){
var arr = [];
for(var i in obj.data){
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(obj.data[i]));
}
return arr.join('&');
}
}
ajax({
url: 'ajax.txt',
data: {
user: 'lihefei',
password: 888888
},
success: function(text){
alert(text);
}
});