AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。php
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。html
AJAX 是与服务器交换数据并更新部分网页的艺术,在不从新加载整个页面的状况下。node
第一步,建立xmlhttprequest对象,ios
var xmlhttp =new XMLHttpRequest();ajax
XMLHttpRequest对象用来和服务器交换数据。chrome
var xhttp;
if (window.XMLHttpRequest) {
//现代主流浏览器
xhttp = new XMLHttpRequest();
} else {
// 针对浏览器,好比IE5或IE6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
复制代码
第二步,使用xmlhttprequest对象的open()和send()方法发送资源请求给服务器。数据库
xmlhttp.open(method,url,async) method包括get编程
和post,url主要是文件或资源的路径,async参数为true(表明异步)或者false(表明同步)json
xhttp.send();使用get方法发送请求到服务器。axios
xhttp.send(string);使用post方法发送请求到服务器。
post 发送请求何时可以使用呢?
(1)更新一个文件或者数据库的时候。
(2)发送大量数据到服务器,由于post请求没有字符限制。
(3)发送用户输入的加密数据。
get例子:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.open("GET", "index.html", true);
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);xhttp.send()
复制代码
post例子
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
复制代码
post表单数据须要使用xmlhttprequest对象的setRequestHeader方法增长一个HTTP头。
post表单例子
xhttp.open("POST", "ajax_test.aspx", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
复制代码
async=true 当服务器准备响应时将执行onreadystatechange函数。
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "index.aspx", true);
xhttp.send();
复制代码
asyn=false 则将不须要写onreadystatechange函数,直接在send后面写上执行代码。
xhttp.open("GET", "index.aspx", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
复制代码
第三步,使用xmlhttprequest对象的responseText或responseXML属性得到服务器的响应。
使用responseText属性获得服务器响应的字符串数据,使用responseXML属性获得服务器响应的XML数据。
document.getElementById("demo").innerHTML = xhttp.responseText;
复制代码
第四步,onreadystatechange函数,当发送请求到服务器,咱们想要服务器响应执行一些功能就须要使用onreadystatechange函数,每次xmlhttprequest对象的readyState发生改变都会触发onreadystatechange函数。
onreadystatechange属性存储一个当readyState发生改变时自动被调用的函数。 readyState属性,XMLHttpRequest对象的状态,改变从0到4,0表明请求未被初始化,1表明服务器链接成功,2请求被服务器接收,3处理请求,4请求完成而且响应准备。 status属性,200表示成功响应,404表示页面不存在。
在onreadystatechange事件中,服务器响应准备的时候发生,当readyState==4和status==200的时候服务器响应准备。
封装代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<script>
//将对象序列化
function params(data) {
var arg = [];
for (var i in data) {
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}
//封装ajax
function ajax(obj) {
//建立xhr对象;
obj.xhr = new XMLHttpRequest();
//后面随机数防止浏览器缓存
obj.url = url + "?rand=" + Math.random();
//序列化对象
obj.data = params(obj.data);
//当是get请求时
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();
}
};
}
//启动HTTP请求
xhr.open(obj.method, obj.url, obj.aysnc);
//当是post请求时
if(obj.method === 'post') {
//模仿表单提交
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//发送HTTP请求-post
xhr.send(obj.data);
} else {
//发送HTTP请求-get
xhr.send(null);
}
//同步调用
if (obj.async == false) {
callback();
}
//回调函数传参
function callback() {
if (xhr.atatus == 200) {
obj.success(xhr.responseText);
} else {
alert("失败,失败状态码:" + xhr.status);
}
}
}
document.addEventListener('click', function() {
ajax({
method: 'get',
url: 'demo3.php',
data: {
'name' = 'Lee',
'age' = 100
},
success: function(text) {
alert(text);
},
async = true
});
}, false);
</script>
</head>
<body>
</body>
</html>
复制代码
promise封装ajax
const getJSON = function (url) {
const promise = new Promise(function (resolve, reject) {
const handler = function () {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
});
return promise;
};
getJSON("/posts.json").then(function (json) {
console.log('Contents: ' + json);
}, function (error) {
console.error('出错了', error);
});
复制代码
fetch 是全局量 window 的一个方法,它的主要特色有:
一、第一个参数是URL:
二、第二个是可选参数,能够控制不一样配置的 init 对象
三、使用了 JavaScript Promises 来处理结果/回调:
// 链式处理,将异步变为相似单线程的写法: 高级用法.
fetch('/some/url').then(function(response) {
return . //... 执行成功, 第1步...
}).then(function(returnedValue) {
// ... 执行成功, 第2步...
}).catch(function(err) {
// 中途任何地方出错...在此处理 :(
});
复制代码
从 fetch()返回的 Promise 将不会拒绝HTTP错误状态, 即便响应是一个 HTTP 404 或 500。相反,它会正常解决 (其中ok状态设置为false), 而且仅在网络故障时或任何阻止请求完成时,它才会拒绝。 能够作简单的封装
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
function parseJSON(response) {
return response.json()
}
fetch('/users')
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('request failed', error)
})
复制代码
默认状况下, fetch在服务端不会发送或接收任何 cookies, 若是站点依赖于维护一个用户会话,则致使未经认证的请求(要发送 cookies,必须发送凭据头). 这一点也能够作一些处理: 若是想要在同域中自动发送cookie,加上 credentials 的 same-origin 选项
fetch(url, {
credentials: ’same-origin' }) 复制代码
same-origin值使得fetch处理Cookie与XMLHttpRequest相似。 不然,Cookie将不会被发送,致使这些请求不保留认证会话。
对于CORS请求,使用include值容许将凭据发送到其余域:
fetch(url, {
credentials: 'include'
})
复制代码
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
复制代码
优缺点:
从 node.js 建立 http 请求
支持 Promise API
客户端支持防止CSRF
提供了一些并发请求的接口(重要,方便了不少的操做)
为何要用axios?
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它自己具备如下特征:
从浏览器中建立 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
取消请求
自动转换JSON数据
客户端支持防止CSRF/XSRF