ajax简介
- Ajax :“Asynchronous Javascript And XML”(异步 JavaScript 和 XML)
ajax的优点
- 无需重新加载整个网页的情况下,能够更新部分网页内容的技术
- 允许根据用户事件来更新部分网页内容
ajax的缺点
- 没有浏览历史,不能回退
- 存在跨域问题,只能访问同源网站内容(解决办法:jsonp/cors设置请求头)
- SEO不友好
ajax的使用方法
原生ajax
- 创建对象:
const xhr = new XMLHttpRequest();
- 设置请求方法:
xhr.open('GET', 'http://localhost:8000/server');
- 发送请求:
xhr.send();
- 处理服务端返回的结果
const btn = document.getElementsByTagName('button');
<script>
btn[0].onclick = function () {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8000/server');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.readyState <= 300) {
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders);
console.log(xhr.response);
result.innerHTML = xhr.response;
} else {
}
}
}
}
</script>
<script>
btn[0].onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8000/server');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('a=100&&b=200&&c=300');
xhr.onreadystatechange = function(){
if(x