JS 交互

AJAX

  GET

          // ajax交互4步骤

        // 1 首先创建ajax的对象 xmlHttpRequest   ----
        // 2 打开open方法 开始交互  open中有三个参数 
                // (1)  请求的方式  GET  POST  网页就这两种请求 
                        // ① GET 明文显示 有大小限制 32kb  优点速度快
                        // ② PODT 加密显示 运行在运行到服务端 显示为2GB 速度慢
        // 3 发送ajax请求 send方法
        // 4 是否请求成功
                // (1)使用XMLHttpRequest中的onreadystatechange 回调函数
                // (2) 其中 readyState 是ajax的状态码 4 表示成功求情
                // (3) status 为服务器状态码(HTTP状态码) 200之间 表示访问成功 300表示页面重定向(缓存)  400之间表示请求错误  500之间表示服务器错误
                // (4) responseText 表示请求返回的字符串文本,后续可以转换对象 或者其他的数据类型
         // (5) 报错 Access to XMLHttpRequest at 'file:///F:/jsTest/1.text' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
            表示请求只能是服务器上的内容 非静态的 使用node可以解决
var xhr=new XMLHttpRequest(); xhr.open('get','1.text',true); xhr.send(); xhr.onreadystatechange=function (){ if(xhr.readyState==4){ if(xhr.status>=200 &&xhr.status<300|| xhr.status==304){ console.log(xhr.responseText); // json.parse(xhr.responseText); 转换JSON对象 } } }

  POST

// POST

        // POST请求比GET请求 多了两个步骤
        //  1.首先GET请求是在open函数中第二个参数中用? &来传递的POST是在send()发送函数中添加的
        // 2.使用POST请求的时候需要添加请求头部 setRequstHeader()
        var xhr=new XMLHttpRequest();
        xhr.open('POST','gethint.php',true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send('a=10&b=20');
        xhr.onreadystatechange=function (){
            if(xhr.readyState==4){
                if(xhr.status>=200 &&xhr.status<300|| xhr.status==304){
                    console.log(xhr.responseText);
                    // json.parse(xhr.responseText);   转换JSON对象
                }
            }
        }

form 交互 在这里就不说了  非常简单  就是利用form标签  get  post

promise  ES6

  

  • promise是一个对象,对象和函数的区别就是对象可以保存状态,函数不可以(闭包除外)
  • 并未剥夺函数return的能力,因此无需层层传递callback,进行回调获取数据
  • 代码风格,容易理解,便于维护
  • 多个异步等待合并便于解决
 
        //promise 对象 两个参数  第一个是成功  第二个是失败

        var p=new Promise((res,rej)=>{
            var xhr=new XMLHttpRequest();
            xhr.open('GET','https://api.github.com/users/chriscoyier/repos',true);
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send();
            xhr.onreadystatechange=function (){
                if(xhr.readyState==4){
                    if(xhr.status>=200 &&xhr.status<300|| xhr.status==304){
                        //请求成功执行成功的res函数
                        res(xhr.responseText);
                    }else{
                        //失败 执行rej函数
                        rej(xhr.responseText);
                    }
                }
            }
        });

        // 执行promise下then函数  遇到then函数  就是promise 第一个箭头函数代表成功要执行的  第二个代表失败要执行的
        p.then(x=>console.log(x),x=>console.log(x));

Fetch ES6

  feich()函数  返回一个promise对象,之后就可以使用promise.then()方法实现数据的输出

使用Fetch获取数据很容易。只需要Fetch你想获取资源。

假设我们想通过GitHub获取一个仓库,我们可以像下面这样使用:

  fetch('https://api.github.com/users/chriscoyier/repos');

Fetch会返回Promise,所以在获取资源后,可以使用.then方法做你想做的。

  fetch('https://api.github.com/users/chriscoyier/repos').then(x=>
            console.log(x)
        );

如果这是你第一次遇见Fetch,也许惊讶于Fetch返回的response。如果console.log返回的response,会得到下列信息:

{
  body: ReadableStream
  bodyUsed: false
  headers: Headers
  ok : true
  redirected : false
  status : 200
  statusText : "OK"
  type : "cors"
  url : "http://some-website.com/some-url"
  __proto__ : Response
}


//可以看出Fetch返回的响应能告知请求的状态。从上面例子看出请求是成功的(ok是true,status是200),但是我们想获取的仓库名却不在这里。

// 显然,我们从GitHub请求的资源都存储在body中,作为一种可读的流。所以需要调用一个恰当方法将可读流转换为我们可以使用的数据。

// Github返回的响应是JSON格式的,所以调用response.json方法来转换数据。

// 还有其他方法来处理不同类型的响应。如果请求一个XML格式文件,则调用response.text。如果请求图片,使用response.blob方法。

// 所有这些方法(response.json等等)返回另一个Promise,所以可以调用.then方法处理我们转换后的数据。
        fetch('https://api.github.com/users/chriscoyier/repos').then(x=>x.json()).then(data=>console.log(data));

可以看出Fetch获取数据方法简短并且简单。

接下来,让我们看看如何使用Fetch发送数据

fetch('some-url', options);

第一个参数是设置请求方法(如postputdel),Fetch会自动设置方法为get

第二个参数是设置头部。因为一般使用JSON数据格式,所以设置ContentTypeapplication/json

第三个参数是设置包含JSON内容的主体。因为JSON内容是必须的,所以当设置主体时会调用JSON.stringify

实践中,post请求会像下面这样:

        let content = {some: 'content'};
        // The actual fetch request
        fetch('some-url', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(content)
        })
 


原文地址:https://www.cnblogs.com/xiaowie/p/13516337.html