当前位置:   article > 正文

Ajax原理&ajax、axios、fetch区别_hmlhttprequest.status 404

hmlhttprequest.status 404

Ajax的原理:
        简单来说,是在用户和服务器之间加了—个中间层(AJAX引擎),通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。使用户操作与服务器响应异步化。这其中最关键的一步就是从服务器获得请求数据。

  1. //1.创建连接
  2. xhr = new XMLHttpRequest();
  3. //2.连接服务器
  4. xhr.open('get', url, true);
  5. //3.发送请求
  6. xhr.send(null);
  7. //4.接受请求
  8. xhr.onreadystatechange = function(){
  9. if(xhr.readyState == 4){
  10. if(xhr.status == 200){
  11. success(xhr.responseText);
  12. } else {
  13. /** false **/
  14. fail && fail(xhr.status);
  15. }
  16. }
  17. }

ajax缺点:

1.安全问题 AJAX暴露了与服务器交互的细节;
2.对搜索引擎的支持比较弱;
3.不容易调试;

ajax优点:

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发送给服务器
  1. function ajax(url, method) {
  2. return new Promise((resolve, reject) => {
  3. const xhr = new XMLHttpRequest() //实例化,以调用方法
  4. xhr.open(method, url, true) //参数1,请求方法。参数2,url。参数3:异步
  5. xhr.onreadystatechange = function () {//每当 readyState 属性改变时,就会调用该函数。
  6. if (xhr.readyState === 4) { //XMLHttpRequest 代理当前所处状态。
  7. if (xhr.status >= 200 && xhr.status < 300) { //200-300请求成功
  8. //JSON.parse() 方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象
  9. resolve(JSON.parse(xhr.responseText))
  10. } else if (xhr.status === 404) {
  11. reject(new Error('404'))
  12. }
  13. } else {
  14. reject('请求数据失败')
  15. }
  16. }
  17. xhr.send(null) //发送hppt请求
  18. })
  19. }
  20. let url = '/data.json'
  21. ajax(url,'get').then(res => console.log(res))
  22. .catch(reason => console.log(reason))

ajax、axios、fetch区别:
        jQuery ajax:

  1. $.ajax({
  2. type: 'POST',
  3. url: url,
  4. data: data,
  5. dataType: dataType,
  6. success: function () {},
  7. error: function () {}
  8. });

axios:

  1. axios({
  2. method: 'post',
  3. url: '/user/12345',
  4. data: {
  5. firstName: 'Fred',
  6. lastName: 'Flintstone'
  7. }
  8. })
  9. .then(function (response) {
  10. console.log(response);
  11. })
  12. .catch(function (error) {
  13. console.log(error);
  14. });

fetch:

  1. try {
  2. let response = await fetch(url);
  3. let data = response.json();
  4. console.log(data);
  5. } catch(e) {
  6. console.log("Oops, error", e);
  7. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/148408
推荐阅读
相关标签
  

闽ICP备14008679号