美文网首页
18.fetch使用案例

18.fetch使用案例

作者: web_jianshu | 来源:发表于2020-05-21 09:51 被阅读0次
    • 案例1
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
      </head>
      <body>
        <script>
          // fetch("url",{option});
          // .then({function(response){} })
          // .catch({function(error){} })
          // var url = "http://127.0.0.1/php&ajax/fetch/test.php?userName=xxf&userPwd=123456";
          // fetch(url)
          //   .then(function(response) {
          //     // 提取响应对象中的json格式数据
          //     // 通过response.code == 0判断
          //     console.log(response);
          //     return response.text();
          //   })
          //   .then(function(text) {
          //     // 管道函数, 接收上一个函数返回的内容
          //     console.log(JSON.parse(text));
          //   })
          //   .catch(function(error) {
          //     // 网络出错或者禁止访问, 404/500无法找到资源不会报错
          //   });
          // 传统ajax
          // var url = "http://127.0.0.1:80/php&ajax/fetch/test.php";
          // var xhr = new XMLHttpRequest();
          // xhr.open("POST", url, true);
          // xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
          // xhr.onload = function() {
          //   console.log(this.responseText);
          //   // console.log(JSON.parse(this.responseText));
          // };
          // xhr.send(`userName=xxf&userPwd=123456`);
          // es6 => fetch
          // var url = "http://127.0.0.1:80/php&ajax/fetch/test.php";
          // fetch(url, {
          //   // 设定请求方法
          //   method: "POST",
          //   headers: {
          //     "content-type": "application/json"
          //   },
          //   // 设定传送的内容
          //   body: JSON.stringify({
          //     userName: "xxf",
          //     userPwd: "123456"
          //   })
          // })
          //   .then(function(response) {
          //     // 提取响应对象中的json格式数据
          //     // 通过response.code == 0判断
    
          //     console.log(response);
    
          //     return response.text();
    
          //   })
    
          //   .then(function(text) {
    
          //     // 管道函数, 接收上一个函数返回的内容
    
          //     console.log(JSON.parse(text));
    
          //   })
    
          //   .catch(function(error) {
    
          //     // 网络出错或者禁止访问, 404/500无法找到资源不会报错
    
          //     console.log(error);
    
          //   });
    
          var url = "http://127.0.0.1:80/php&ajax/fetch/test.php";
    
          fetch(url, {
    
            // 设定请求方法
    
            method: "POST",
    
            headers: {
    
              "content-type": "application/x-www-form-urlencoded"
    
            },
    
            // 设定传送的内容
    
            body: `userName=xxf&userPwd=123456`
    
          })
    
            .then(function(response) {
    
              // 提取响应对象中的json格式数据
    
              // 通过response.code == 0判断
    
              console.log(response);
    
              return response.text();
    
            })
    
            .then(function(text) {
    
              // 管道函数, 接收上一个函数返回的内容
    
              console.log(text);
    
            })
    
            .catch(function(error) {
    
              // 网络出错或者禁止访问, 404/500无法找到资源不会报错
    
              console.log(error);
    
            });
    
        </script>
    
      </body>
    
    </html>
    
    • 案例2
    <!DOCTYPE html>
    
    <html lang="en">
    
      <head>
    
        <meta charset="UTF-8" />
    
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    
        <title>Document</title>
    
      </head>
    
      <body>
    
        <script>
    
          //   // 传统ajax
    
          //   var xhr = new XMLHttpRequest();
    
          //   xhr.open("GET", "./time.php");
    
          //   xhr.send();
    
          //   // onload 是 HTML5  中提提供的 XMLHttpRequest version2.0 定义的  相当于xhr.readyState === 4 状态
    
          //   xhr.onload = function() {
    
          //     console.log(this.readyState);
    
          //     console.log(this.responseText);
    
          //   };
    
          // es6 => fetch
    
          //   fetch("./debug.php?name=Tom&age=20", {
    
          //     method: "GET"
    
          //   })
    
          //     .then(res => {
    
          //       return res.text();
    
          //     })
    
          //     .then(text => {
    
          //       console.log(text);
    
          //     })
    
          //     .catch(err => {
    
          //       console.log(err);
    
          //     });
    
        </script>
    
      </body>
    
    </html>
    
    • 案例3
    <!DOCTYPE html>
    
    <html lang="en">
    
      <head>
    
        <meta charset="UTF-8" />
    
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    
        <title>Document</title>
    
      </head>
    
      <body>
    
        <ul id="list"></ul>
    
        <script>
    
          var list = document.getElementById("list");
    
          // es6 => fetch
    
          fetch("./users.php", {
    
            method: "GET"
    
          })
    
            .then(res => {
    
              return res.text();
    
            })
    
            .then(text => {
    
              console.log(JSON.parse(text));
    
              var data = JSON.parse(text);
    
              for (var i = 0; i < data.length; i++) {
    
                var li = document.createElement("li");
    
                li.innerHTML = data[i].name;
    
                li.id = data[i].id;
    
                list.appendChild(li);
    
                li.addEventListener("click", function() {
    
                  fetch(`users.php?id=${this.id}`)
    
                    .then(res => {
    
                      return res.text();
    
                    })
    
                    .then(text => {
    
                      console.log(JSON.parse(text).age);
    
                    })
    
                    .catch(err => {
    
                      console.log(err);
    
                    });
    
                });
    
              }
    
            })
    
            .catch(err => {
    
              console.log(err);
    
            });
    
          // 发送请求获取列表数据呈现在页面
    
          // ================传统ajax====================
    
          //   var xhr = new XMLHttpRequest();
    
          //   xhr.open("GET", "./users.php");
    
          //   xhr.send();
    
          //   xhr.onreadystatechange = function() {
    
          //     if (this.readyState !== 4) return;
    
          //     var data = JSON.parse(this.responseText);
    
          //     // data => 数据
    
          //     for (var i = 0; i < data.length; i++) {
    
          //       var li = document.createElement("li");
    
          //       li.innerHTML = data[i].name;
    
          //       li.id = data[i].id;
    
          //       list.appendChild(li);
    
          //       li.addEventListener("click", function() {
    
          //         // TODO: 通过JAX操作获取服务端对应的数据信息
    
          //         // 如何获取当前被点击元素对应的数据的ID
    
          //         // console.log(data[i])  undefined
    
          //         // console.log(this.id)
    
          //         var xhr1 = new XMLHttpRequest();
    
          //         xhr1.open("GET", "users.php?id=" + this.id);
    
          //         xhr1.send();
    
          //         xhr1.onreadystatechange = function() {
    
          //           if (this.readyState !== 4) return;
    
          //           var obj = JSON.parse(this.responseText);
    
          //           console.log(obj.age);
    
          //         };
    
          //       });
    
          //     }
    
          //   };
    
          // 给每一个 li 注册点击事件
    
          // 因为 li 后来动能创建,所以不能这样注册事件
    
          // for (var i = 0; i < list.children.length; i++) {
    
          //     list.children[i].addEventListener('click', function () {
    
          //         console.log(111)
    
          //     })
    
          // }
    
          // var xhr  = new XMLHttpRequest()
    
          // // 这里仍然是使用 URL 中的问好参数传递数据
    
          // xhr.open('GET', 'users.php?id=2')
    
          // xhr.send(null)
    
          // xhr.onreadystatechange = function () {
    
          //     if (this.readyState !== 4) return
    
          //     console.log(this.responseText)
    
          // }
    
        </script>
    
      </body>
    
    </html>
    
    • 案例4
    
    
    <!DOCTYPE html>
    
    <html lang="en">
    
      <head>
    
        <meta charset="UTF-8" />
    
        <title>动态渲染数据到表格中</title>
    
        <style>
    
          td {
    
            white-space: nowrap;
    
            padding-right: 10px;
    
            box-sizing: border-box;
    
          }
    
        </style>
    
      </head>
    
      <body>
    
        <table>
    
          <tbody id="content"></tbody>
    
        </table>
    
        <script>
    
          var tbody = document.querySelector("#content");
    
          // 传统ajax
    
          // var xhr = new XMLHttpRequest();
    
          // xhr.open("GET", "test.php");
    
          // xhr.send();
    
          // xhr.onreadystatechange = function() {
    
          //   if (this.readyState !== 4) return;
    
          //   var res = JSON.parse(this.responseText);
    
          //   // res => 服务端返回的数据
    
          //   var data = res.data;
    
          //   console.log(data);
    
          //   for (var i = 0; i < data.length; i++) {
    
          //     // 先创建行
    
          //     // 再创建列
    
          //     // 再将列添加到行
    
          //     // 再将行添加到tbody
    
          //     // console.log(data[i])
    
          //     var tr = document.createElement("tr");
    
          //     tr.innerHTML =
    
          //       "<td>" +
    
          //       data[i][0] +
    
          //       "</td><td>" +
    
          //       data[i][1] +
    
          //       "</td><td>" +
    
          //       data[i][2] +
    
          //       "</td><td>" +
    
          //       data[i][3] +
    
          //       "</td><td>" +
    
          //       data[i][4] +
    
          //       "</td><td>" +
    
          //       data[i][5] +
    
          //       "</td><td>" +
    
          //       data[i][6] +
    
          //       "</td><td>" +
    
          //       data[i][7] +
    
          //       "</td><td>" +
    
          //       data[i][8] +
    
          //       "</td>";
    
          //     tbody.appendChild(tr);
    
          //   }
    
          // };
    
          // es6 => fetch
    
          fetch("test.php", {
    
            method: "GET"
    
          })
    
            .then(res => {
    
              return res.text();
    
            })
    
            .then(text => {
    
              var res = JSON.parse(text);
    
              console.log(res);
    
              if (res.code != 0) {
    
                return console.log("获取数据失败");
    
              }
    
              var data = res.data;
    
              data.map(item => {
    
                var tr = document.createElement("tr");
    
                tr.innerHTML = `<td>${item[0]}</td><td>${item[1]}</td><td>${item[2]}</td><td>${item[3]}</td><td>${item[4]}</td><td>${item[5]}</td><td>${item[6]}</td><td>${item[7]}</td><td>${item[8]}</td>`;
    
                tbody.appendChild(tr);
    
              });
    
            })
    
            .catch(err => {
    
              console.log(err);
    
            });
    
        </script>
    
      </body>
    
    </html>
    
    • 案例5
    <!DOCTYPE html>
    
    <html lang="en">
    
      <head>
    
        <meta charset="UTF-8" />
    
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    
        <title>Document</title>
    
      </head>
    
      <body>
    
        <script>
    
          // 传统ajax
    
          //   var xhr = new XMLHttpRequest();
    
          //   xhr.open("GET", "test.php");
    
          //   xhr.send();
    
          //   // 我们通过代码告诉请求代理对象(xhr),服务端请求响应给我们的是 JSON 然后才会根据响应头的content-type进行 JSON 字符串的自动解析
    
          //   xhr.responseType = "json";
    
          //   xhr.onreadystatechange = function() {
    
          //     if (this.readyState !== 4) return;
    
          //     console.log(this.response.data);
    
          //     // this.response 获取到的结果会根据 this.responseType 的变化而变化
    
          //     // this.responseText 永远获取的是字符串形式的响应体
    
          //   };
    
          // es6 => fetch
    
          fetch("test.php", {
    
            method: "GET"
    
          })
    
            .then(res => {
    
              return res.text();
    
            })
    
            .then(text => {
    
              console.log(JSON.parse(text));
    
            })
    
            .catch(err => {
    
              console.log(err);
    
            });
    
        </script>
    
      </body>
    
    </html>
    
    • 案例6
    <!DOCTYPE html>
    
    <html lang="en">
    
      <head>
    
        <meta charset="UTF-8" />
    
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    
        <title>AJAX 系统表格渲染</title>
    
        <style>
    
          td {
    
            white-space: nowrap;
    
          }
    
        </style>
    
      </head>
    
      <body>
    
        <table id="demo"></table>
    
        <!-- 
    
            script 标签的特点是
    
            1. innerHTML 永远不会显示在界面上
    
            2. 如果 type 不等于 text/javascrip 的话,内部的内容不会作为 JavaScript 代码执行
    
         -->
    
        <script id="tmpl" type="txet/x-art-template">
    
          {{ each comments }}
    
          <tr>
    
              <td>{{ $value.author }}</td>
    
              <td>{{ $value.content }}</td>
    
              <td>{{ $value.created }}</td>
    
          </tr>
    
          {{ /each }}
    
        </script>
    
        <!-- 在浏览器端使用 -->
    
        <script src="template-web.js"></script>
    
        <script>
    
          // 传统ajax
    
          //   var xhr = new XMLHttpRequest();
    
          //   xhr.open("GET", "test.php");
    
          //   xhr.send();
    
          //   xhr.onreadystatechange = function() {
    
          //     if (this.readyState !== 4) return;
    
          //     var res = JSON.parse(this.responseText);
    
          //     // 模版引擎所需数据
    
          //     var context = { comments: res.data };
    
          //     // 借助模版引擎
    
          //     var html = template("tmpl", context);
    
          //     console.log(html);
    
          //     document.getElementById("demo").innerHTML = html;
    
          //     // 1. 选择一个模版引擎
    
          //     // https://github.com/tj/consolidate.js#supported-template-egines
    
          //     // 2. 下载模版引擎JS文件
    
          //     // 3. 引入到页面中
    
          //     // 4. 准备一个模版
    
          //     // 5. 准备一个数据对象
    
          //     // 6. 通过模版引擎的JS提供的一个函数将模版和数据整合得到渲染结果HTML
    
          //     // 7. 将渲染结果的 HTML 设置到 默认元素的 innerHTML 中
    
          //     // var tmpl = '{{if user}}<h2>{{user.name}}</h2>{{/if}}'
    
          //     // 为什么使用script写模版
    
          //     // 1. 如果将模版写到JS中,维护不方便,不能换行,没有着色
    
          //   };
    
          // es6 => fetch
    
          fetch("test.php", {
    
            method: "GET"
    
          })
    
            .then(res => {
    
              return res.text();
    
            })
    
            .then(text => {
    
              var res = JSON.parse(text);
    
              console.log(res);
    
              if (res.code !== 0) {
    
                return console.log("获取数据失败");
    
              }
    
              var context = { comments: res.data };
    
              var html = template("tmpl", context);
    
              document.getElementById("demo").innerHTML = html;
    
            })
    
            .catch(err => {
    
              console.log(err);
    
            });
    
        </script>
    
      </body>
    
    </html>
    ```w

    相关文章

      网友评论

          本文标题:18.fetch使用案例

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