4步:
//1. 实例化xhr对象var xhr = new XMLHttpRequest();//2. 调用open方法准备ajax请求//参数1: 请求方式 (get、post、delete、put)//参数2: 请求的服务器端的地址//参数3: true(异步、默认)、false(同步)xhr.open('get', '/getData');//3. 调用send方法发送ajax请求xhr.send();//4. 调用onload事件,配合responseText来接收服务器端返回的数据// xhr.responseText: 以字符串形式来接收服务器端返回的结果// 服务器端返回的数据有两种可能:// 1) 普通字符串(hello world \ I am xiaoming)// 2) json字符串('{"id":"101", type:"goods", "name":"小米"}')// json字符串都会使用 JSON.parse 转回成对象形式xhr.onload = function () { xhr.responseText}
get参数要拼接在url地址的后面,以?进行分割
var xhr = new XMLHttpRequest();//参数2的位置用来拼接get参数, 以 ? 作为分隔符// ?之前: 请求的url地址// ?之后: 查询参数 key1=value1&key2=value2&...xhr.open('get', '/getData?id=1&name=zs&age=20&...');xhr.send();xhr.onload = function () { xhr.responseText}
post传参有三种方式: key=value&key=value&... FormData json字符串
//1. key=value&key=value&...// application/x-www-form-urlencoded : 需要key=value这种结构的参数var xhr = new XMLHttpRequest();xhr.open('post', '/postData');//将发送到服务器端的数据写成一个字符串var str = 'id=1&name=zs&age=20&...'//发送请求之前一定要设置请求头为 application/x-www-form-urlencodedxhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');xhr.send(str);xhr.onload = function () { xhr.responseText}
//2. 发送FormData类型的数据//1) 直接获取整个post表单的数据var fm = document.querySelector('form');var fd = new FormData(fm)//2) 实例化一个空的FormData,再向里面append数据var fd = new FormData();fd.append('name', 'xiaoming');fd.append('age', 20);fd.append('img', this.files[0]);//发送ajax请求时,如果发送到服务器端的数据为FormData时,不需要设置请求头,需要将fd作为参数传入sendvar xhr = new XMLHttpRequest();xhr.open('post', '/postData');xhr.send(fd);xhr.onload = function () { xhr.responseText}
//3. 发送到服务器端的数据是json字符串var jsonStr = JSON.stringify({name:"zs", age:20}); //'{name:"zs", age:20}'var xhr = new XMLHttpRequest();xhr.open('post', '/postData');xhr.setRequestHeader('content-type', 'application/json');xhr.send(jsonStr);xhr.onload = function () { xhr.responseText}
联系客服