赞
踩
- //1.创建连接
- xhr = new XMLHttpRequest();
- //2.连接服务器
- xhr.open('get', url, true);
- //3.发送请求
- xhr.send(null);
- //4.接受请求
- xhr.onreadystatechange = function(){
- if(xhr.readyState == 4){
- if(xhr.status == 200){
- success(xhr.responseText);
- } else {
- /** false **/
- fail && fail(xhr.status);
- }
- }
- }

1.安全问题 AJAX暴露了与服务器交互的细节;
2.对搜索引擎的支持比较弱;
3.不容易调试;
1.通过异步模式,提升了用户体验;
2.Ajax在客户端运行,承担了一部分本来由服务器承担的工作,减少了大用户量下的服务器负载;
3.Ajax可以实现动态不刷新(局部刷新);
基于Promise封装Ajax:
- 返回一个新的Promise实例
- 创建HMLHttpRequest异步对象
- 调用open方法,打开url,与服务器建立链接(发送前的一些处理)
- 监听Ajax状态信息
- 如果xhr.readyState == 4(表示服务器响应完成,可以获取使用服务器的响应了)
5.1 xhr.status == 200,返回resolve状态
5.2 xhr.status == 404,返回reject状态- xhr.readyState !== 4,把请求主体的信息基于send发送给服务器
- function ajax(url, method) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest() //实例化,以调用方法
- xhr.open(method, url, true) //参数1,请求方法。参数2,url。参数3:异步
- xhr.onreadystatechange = function () {//每当 readyState 属性改变时,就会调用该函数。
- if (xhr.readyState === 4) { //XMLHttpRequest 代理当前所处状态。
- if (xhr.status >= 200 && xhr.status < 300) { //200-300请求成功
- //JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象
- resolve(JSON.parse(xhr.responseText))
- } else if (xhr.status === 404) {
- reject(new Error('404'))
- }
- } else {
- reject('请求数据失败')
- }
- }
- xhr.send(null) //发送hppt请求
- })
- }
- let url = '/data.json'
- ajax(url,'get').then(res => console.log(res))
- .catch(reason => console.log(reason))

- $.ajax({
- type: 'POST',
- url: url,
- data: data,
- dataType: dataType,
- success: function () {},
- error: function () {}
- });
axios:
- axios({
- method: 'post',
- url: '/user/12345',
- data: {
- firstName: 'Fred',
- lastName: 'Flintstone'
- }
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
fetch:
- try {
- let response = await fetch(url);
- let data = response.json();
- console.log(data);
- } catch(e) {
- console.log("Oops, error", e);
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。