什么是ajax
-
ajax全称为Asynchronous JavaScript and XML(异步JavaScript和XML)
-
ajax的核心有Javascript、DOM、XMLHTTPRequest(js的一个内置对象)。
-
通过XMLHTTPRequest发起异步请求,请求成功后拿到数据,然后会通过js操作DOM,然后把数据展示到页面中
-
ajax不是一门新技术,是一系列技术的组合
XMLHttpRequest对象
XMLHttpRequest对象的方法
XMLHttpRequest对象的属性
ajax的get请求
客户端常见请求方式
1.在浏览器中输入网址发出get请求;
2.css,js,img自动发出get请求;
3.超连接发出get请求
<a href= 'getUser?name=wgr&pwd=123’>得到用户</a>(get);
4.js发出get请求
window.location.href= 'url?name=wgr&pwd=123';
5.表单提交发出请求(get或post);
6.ajax请求(get或post
console.log(1);
let xhr = new XMLHttpRequest();
console.log(xhr);
// 和服务器建立连接,通过路由在router.js获得controller里面的**文件里面的对应响应内容
xhr.open('GET','http://127.0.0.1:8000/login?account=15656565656&passwd=123456'); //前端向后端传数据?account=15656565656&passwd=123456(url间传值)
xhr.responseType = 'json'; //设置后端响应给前端内容的类型
// 发起请求
xhr.send();
// 监听请求过程
xhr.onreadystatechange = function(){
// 0 1 2 3 4(完成)
console.log(xhr.readyState);
if(xhr.readyState == 4){
console.log('status:',xhr.status);
if(xhr.status == 200){//请求成功
console.log("请求完成并且成功了,数据:", xhr.response);
//alert(xhr.response.data);
}
}
console.log(2);
//1 xhr{...} 2 2 3 4 status:200 请求完成并且成功了,数据:{...}
//所以XMLHTTPRequest发起的是异步请求
ajax的post请求
let xhr = new XMLHttpRequest();
console.log(xhr);
// 和服务器建立连接
xhr.open('POST','http://127.0.0.1:8000/register');
// 设置请求头 post请求需要设置请求头,不然后端接收不到数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 设置响应数据类型
xhr.responseType = 'json';
//设置请求头和设置响应数据类型必须在发起请求前
// 发起请求
xhr.send(`account=15656565656&passwd=123456`);
// 监听请求过程
xhr.onreadystatechange = function(){
// 0 1 2 3 4(完成)
// console.log(xhr.readyState);
if(xhr.readyState == 4){
console.log('status:',xhr.status);
if(xhr.status == 200){//请求成功
console.log("请求完成并且成功了,数据:", xhr.response);
}
}
}
get请求和post的区别
get
1.传递数据方式:数据在请求资源地址的后面(请求头里面)
2.传递数据大小:4k左右
3.安全性:一点都不安全
post
1.传递数据方式:放在请求体里面的
2.传递数据大小:几乎没有限制
3.安全性:相对来说安全一点
4.文件上传必须用post
浏览器地址栏里面直接输入地址发起请求默认为get请求