美文网首页
Ajax学习

Ajax学习

作者: 大佬教我写程序 | 来源:发表于2021-07-07 22:42 被阅读0次
响应消息格式

Ajax就是异步的js和XML

  • 使用Ajax的优势是:无需刷新就可以获得数据 ,可以根据用户事件来更新页面的内容
    缺点:1. 没有浏览历史,不能后退 2. 存在跨域问题 3. SEO(搜索引擎优化)不友好(搜索引擎找不到)
  • 非编程语言
XML简介

XML可扩展标记语言,用于传输和存储数据,里面都是自定义标签,用来表示一些数据,现在已经被JSON取代了


image.png
HTTP超文本传输协议,规定了浏览器和万维网之间互相通信的规则
  1. 请求报文
    行 GET /

    空行
  2. 响应报文
    行 HTTP/1.1 200 OK

    空行

Ajax的get请求

  <style>
    #result {
      height: 100px;
      width: 150px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <button>点击发送请求</button>
  <div id="result"></div>
  <script>
    const btn = document.getElementsByTagName('button')[0];
    const result = document.getElementById('result');
    btn.onclick = function() {
      console.log('btn click');
      //创建对象
      const xhr = new XMLHttpRequest();
      //初始化,设置请求的方法和URL
      xhr.open('GET', 'http://127.0.0.1:3000');
      //发送
      xhr.send();
      //事件绑定 处理服务端返回的结果
      //readystate 是 xhr 对象的属性,表示状态:
      // 0(未初始化)1(open方法调用完毕)2(send方法调用完毕)3(服务端返回部分结果)4(服务端返回了所有的结果)
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            //处理结果
            //响应
            //  xhr.status 状态码
            //  xhr.statusText  状态字符串
            //  xhr.getAllResponseHeaders() 所有响应头
            //  xhr.response   响应体
            console.log(xhr.status);
            console.log(xhr.statusText);
            console.log(xhr.getAllResponseHeaders());
            result.innerHTML = xhr.response;
          } else {

          }
        }
      }
    }
  </script>
</body>

Ajax的post请求

  <style>
    #result {
      width: 100px;
      height: 150px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <div id="result">

  </div>
  <script>
    //获取DOM元素
    const result = document.getElementById('result');
    //绑定事件
    result.onmouseover = function() {
      console.log('mouseover');
      //创建对象
      const xhr = new XMLHttpRequest();
      //初始化 绑定URL路径
      xhr.open('POST', 'http://127.0.0.1:3000');
      //发送
      //可设置发送的信息后缀    xhr.send('a=100&b=200&c=300');
      xhr.send();
      //事件绑定
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response;
          } else {
            console.log('请求失败');
          }
        }
      }
    }
  </script>
</body>

设置请求体

image.png

设置消息体

2:OPTIONS校验,所以要再发一个请求3


image.png

Ajax响应json格式的信息

  <script>
    const result = document.getElementById('result')
    window.onkeydown = function() {
      // console.log(window);
      console.log('keydown');
      //发送请求
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'json'
      xhr.open('GET', 'http://127.0.0.1:3000/json-server');
      //发送
      xhr.send();
      //事件绑定
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            console.log(xhr.response);
            result.innerHTML = xhr.response.name
          }

        }
      }
    }
  </script>

关于ie浏览器不能实时响应真实刚改变的内容,只需如下操作

  • 让他知道我们不是一个时间戳请求的服务
 xhr.open('GET', 'http://127.0.0.1:3000/ie?t=' + Date.now())

请求超时和网络异常的处理

超时和异常

请求取消(send()函数调用之后使用)

xhr.abort();

关于用户重复点击请求服务器而造成服务器压力大的解决办法

  • 在用户第二次请求服务时,取消上一次的请求
 btn1.onclick = function() {
      //如果已经发送完了将上面一个请求清除掉
      if (issending) {
        xhr.abort();
      }
      issending = true;
      xhr = new XMLHttpRequest();
      xhr.open('GET', 'http://127.0.0.1:3000/delay');
      xhr.send();
      //判断是否已经发送完了
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          issending = false;
        }
      }
    }

ajax在jq里面的使用

  • 通过cdn的方式引入jq
  • cdn引入的网址 [https://www.bootcdn.cn/](https://www.bootcdn.cn/)
  • get post 通用性
  <script>
    $('button').eq(0).click(function() {
      //get(url,发送的信息,回调函数,返回值转换为的类型(JSON))
      $.get('http://127.0.0.1:3000/jqajax', {
        a: 100,
        b: 200
      }, function() {
        console.log('jqajax1');
      })
    })
    $('button').eq(1).click(function() {
      $.post('http://127.0.0.1:3000/jqajax', {
        a: 100,
        b: 200
      }, function() {
        console.log('jqajax2');
      })
    })
    $('button').eq(2).click(function() {
      $.ajax({
        url: 'http://127.0.0.1:3000/jqajax',
        data: "{a:100,b:200}",
        type: 'GET',
        dataType: 'json',
        //data是服务端返回的数据
        success: function(data) {
          console.log(data);
        },
        //超时回调世间
        timeout: 2000,
        //失败回调
        error: function() {
          console.log('请求失败');
        }
      })
    })
  </script>

将原生ajax封装成promise

var myNewAjax = function (url) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest()
    xhr.open('get', url)
    xhr.send(data)
    xhr.onreadystatechange = function () {
      if (xhr.status == 200 && readyState == 4) {
        var json = JSON.parse(xhr.responseText)
        resolve(json)
      } else if (xhr.readyState == 4 && xhr.status != 200) {
        reject('error')
      }
    }
  })
}

相关文章

  • ajax学习笔记

    Ajax学习笔记 Ajax简介 1. Ajax是什么? Ajax : Asynochronous javascri...

  • 2018-11-06

    学习ajax

  • Python网络爬虫(三)

    AJAX学习 AJAX=Asynchronous JavaScript and XML(异步的 JavaScrip...

  • 2018-11-07

    继续学习Ajax

  • 2018-11-09

    ajax学习完毕

  • AJAX

    前端学习中,今天学习了blue老师视频里面的ajax,仅作为自己学习的记录 ajax(Asynchronous J...

  • HTML5学习小记二ajax,window.orientatio

    1.ajax的学习 HTML5中的ajax相当于iOS中的afnetworking;详见jQuery ajax -...

  • jQuery AJAX

    本节我们学习 AJAX,AJAX 是 Asynchronous Javascript And XML 的首字母缩写...

  • JavaWeb学习-Ajax-1-Ajax简介

    JavaWeb学习-Ajax-1-Ajax简介 进入到一个新的知识点的学习,这个知识点叫做Ajax,指的是异步的j...

  • Ajax学习

    title: Ajax学习notebook: 编程tags:javascript 只会iOS已经不行了,要学习各种...

网友评论

      本文标题:Ajax学习

      本文链接:https://www.haomeiwen.com/subject/samiultx.html