JavaScrip之初识Ajax

作者: 庄海鑫 | 来源:发表于2017-09-21 00:39 被阅读0次

    什么是Ajax?

    ajax是一种技术方案,但并不是一种新技术。它依赖的是现有的CSS/HTML/Javascript,而其中最核心的依赖是浏览器提供的XMLHttpRequest对象,是这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。 实现在页面不刷新的情况下和服务端进行数据交互


    如何实现Ajax?

    • XMLHttpRequest对象
    • fetch

    XMLHttpRequest的用法、属性

    1.创建XHR对象

    var xhr = new XMLHttpRequest();
    

    2.xhr.open()

    接受三个参数

    • 1.要发送的请求的类型("get"、"post"),
      1. 请求的URL
      1. 是否异步发送请求的布尔值

    3.xhr.send()

    接受一个参数

    • 1.请求主体发送的数据,不需要则传入(null)

    4.xhr.responseText:作为响应主体被返回的文本

    5.xhr.responseXML:如果响应的内容类型是"text/html"或"application/xml",这个属性中将保存包含着响应数据的XML DOM文档

    6.xhr.status:响应的HTTP状态

    7.xhr.statusText:HTTP状态的说明

    8.xhr.readyState:请求/响应过程的当前活动阶段

    • 0:未初始化。尚未调用open()方法。
    • 1:启动。已经调用open()方法,但尚未调用send()方法。
    • 2:发送。已经调用send()方法,但尚未接收到响应。
    • 3:接收。已经接收到部分响应数据。
    • 4:完成。已经接收到全部数据,而且已经可以在客户端使用。
      说明:可以把xhr.readyState属性和TCP/IP的三次握手类比一下,1,2表示第一次,3表示第二次,4表示第三次。只要readyState属性变一次,就会触发一次readyState事件。还要强调一点的是必须在调用open()之前指定onreadystatechage事件处理程序才能确保跨浏览器兼容性。

    9.xhr.abort():取消异步请求,在接收响应之前使用

    10.xhr.setRequestHeader():设置自定义的请求头部信息。

    在调用open()方法之后,send()方法之前使用。

    11.xhr.timeout:表示请求在等待响应多少毫秒之后就终止。

    12.xhr.overrideMimeType():用于重写响应的MIME类型。

    比如服务器返回的MIME类型时text/plain,但数据实际包含的是XML,根据MIME类型,即使数据是XML,responseXML属性仍然是null,通过调用该方法,可以保证把响应当作XML而非纯文本使用。调用方法必须在send()之前使用

    var xhr = new XMLHttpReququest()
    xhr.open("get","text.php",true)
    xhr.overrideMimeType("text/html")
    xhr.send(null)
    

    具体实现Ajax

    1.同步实现Ajax

    hello.html

        //同步执行Ajax
        var xhr=new XMLHttpRequest();
        xhr.open('GET','/hello.json',false);
        xhr.send();
        var data=xhr.responseText;
        console.log(data);
    

    hello.json

    {
      "name":"Ajax"
    }
    

    首先我们打开命令行本地服务器,不然会报错。

    报错

    接下来执行


    大家可以看到红色框的英文,大概意思就是主线程上的同步XMLHttpRequest由于对最终用户体验的不利影响而被淘汰。如需更多帮助,请检查。所以我们需要使用异步执行Ajax


    2. 请求方式为GET异步实现Ajax

    hello.html

     //   异步执行Ajax
        var xhr=new XMLHttpRequest();
        xhr.open('GET','/hello.json',true);
        xhr.send();
        xhr.addEventListener('load',function(){
        var data=xhr.responseText;
        console.log(data);
        });
    

    hello.json

    {
      "name":"Ajax"
    }
    
    image.png

    大家注意一下,这里用Ajax向本地服务器请求的是/hello.json ,返回的数据类型是什么?是json对象还是什么?我们可以验证一下。在源代码添加一句 typeof data

    image.png

    结果为string


    假如我们在open()当中输入错误的会发现什么状况呢?

    404 not found
    可以看到404 not found,404是http状态码,最开始执行成功状态码为200,于是我们可以继续改进代码,通过状态码判断是否执行
    hello.html
       var xhr=new XMLHttpRequest();
        xhr.open('GET','/hello.json',true);
        xhr.send();
      
        xhr.addEventListener('load',function(){
          console.log(xhr.status);
          if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
          var data=xhr.responseText;
          console.log(data);
          }
          else{ 
            console.log('error');
          }
        });
        //当网络出现故障的时候
        xhr.error=function(){
          console.log("error");
        }
    
    当文件路径没有出错的时候

    假如我们要监听当前执行的状态,该怎么做?
    hello.html

        //监听状态
        var xhr=new XMLHttpRequest();
    
        console.log('readystatus:',xhr.readyState);
        //使用readystatechange事件监听状态
        xhr.addEventListener('readystatechange',function(){
          console.log('readystatus:',xhr.readyState);
        })
        xhr.addEventListener('load',function(){
          console.log(xhr.status);
          if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
          var data=xhr.responseText;
          console.log(data);
          }
          else{ 
            console.log('error');
          }
        });
        xhr.open('GET','/hello.json',true);
        xhr.send();
    

    如果路径出错则是下图这种状况

    image.png

    由于是错误的路径,所以没有readyState:3,因为3表示接受响应数据,这步是不可能有的。

    3.请求方式为POST异步实现Ajax

      var xhr = new XMLHttpRequest()
      xhr.timeout = 3000        //可选,设置xhr请求的超时时间
      xhr.open('POST', '/login', true)
    
      xhr.onload = function(e) { 
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
          console.log(this.responseText)
        }
      }
        //可选
      xhr.ontimeout = function(e) { 
            console.log('请求超时')
      }
    
      //可选
      xhr.onerror = function(e) {
          console.log('连接失败')
      }
      //可选
      xhr.upload.onprogress = function(e) {
          //如果是上传文件,可以获取上传进度
      }
    
      xhr.send('username=jirengu&password=123456')  
    

    POST方式将数据放到send()中

    4.封装Ajax

      function ajax(opts){
        var url = opts.url
        var type = opts.type || 'GET'
        var dataType = opts.dataType || 'json'
        var onsuccess = opts.onsuccess || function(){}
        var onerror = opts.onerror || function(){}
        var data = opts.data || {}
    
        var dataStr = []
        for(var key in data){
            dataStr.push(key + '=' + data[key])
        }
        dataStr = dataStr.join('&')
    
        if(type === 'GET'){
            url += '?' + dataStr
        }
    
        var xhr = new XMLHttpRequest()
        xhr.open(type, url, true)
        xhr.onload = function(){
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                //成功了
                if(dataType === 'json'){
                    onsuccess( JSON.parse(xhr.responseText))
                }else{
                    onsuccess( xhr.responseText)
                }
            } else {
                onerror()
            }
        }
        xhr.onerror = onerror
        if(type === 'POST'){
            xhr.send(dataStr)
        }else{
            xhr.send()
        }
    }
    
    ajax({
        url: 'http://api.jirengu.com/weather.php',
        type:'POST',
        dataType:'TEXT',
        data: {
            city: '北京'
        },
        onsuccess: function(ret){
            console.log(ret)
            render(ret)  //浏览器渲染
        },
        onerror: function(){
            console.log('服务器异常')
            showError()   //错误浏览器渲染
        }
    })
    function render(json){
        //拼装成dom输入页面中
    }
    function showError(){
      //错误提示
    }
    

    sever mock

    相关文章

      网友评论

        本文标题:JavaScrip之初识Ajax

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