fetch网络请求、axios网络请求

目录

一、fetch网络请求(了解)

1.1 fetch的基本使用

1.2 get请求方式

1.3 post请求方式

1.4 fetch的简单封装

二、axios网络请求(常用)

2.1 axios特点

2.2 GET请求

2.3 POST请求

2.4  直接使用axios发起请求

2.5 全局的 axios 默认值

 


 

一、fetch网络请求(了解)

fetch和Ajax一样都是用于请求网络数据的

fetch是es6新增的,基于promise的网络请方法

1.1 fetch的基本使用

        fetch(url,{options})

        .then()

        .catch();


1.2 get请求方式

    fetch("./41.php?teacher=lwj&age=20", {
        method: "get"
    }).then(function (res) {
        // console.log(res);
        // console.log(res.text());
        // return res.text();
        return res.json();
    }).then(function (data) {
        console.log(data);
        console.log(typeof data);
    }).catch(function (e) {
        console.log(e);
    });

41.php,

<?php
$teacher = $_GET["teacher"];
$age = $_GET["age"];
$arr = array("name"=>$teacher, "age"=>$age);
$data = json_encode($arr);
echo $data;
?>


1.3 post请求方式

    fetch("./41.php", {
        method: "post",
        body: JSON.stringify({teacher:"zq", age:666})
    }).then(function (res) {
        // console.log(res.text());
        // return res.text();
        return res.json();
    }).then(function (data) {
        console.log(data);
        console.log(typeof data);
    }).catch(function (e) {
        console.log(e);
    });

41.php,

<?php

$rws_post = $GLOBALS["HTTP_RAW_POST_DATA"];
$mypost = json_decode($rws_post);
$teacher = (string)$mypost->teacher;
$age = (string)$mypost->age;
$arr = array("name"=>$teacher, "age"=>$age);
$data = json_encode($arr);
echo $data;

?>


1.4 fetch的简单封装

    class EasyHttp{
        static obj2str(data) {
            data = data || {};
            data.t = new Date().getTime();
            var res = [];
            for(var key in data){
                res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
            }
            return res.join("&");
        }
        static get(url, params){
            return new Promise(function (resolve, reject) {
                let newUrl = url;
                if(params !== undefined && params instanceof Object){
                    let str = EasyHttp.obj2str(params);
                    newUrl += "?" + str;
                }
                fetch(newUrl, {
                    method: "get"
                }).then(function (res) {
                    resolve(res.json());
                }).catch(function (e) {
                    reject(e);
                })
            })
        }
        static post(url, params){
            return new Promise(function (resolve, reject) {
                fetch(url, {
                    method: "post",
                    body: JSON.stringify(params)
                }).then(function (res) {
                    resolve(res.json());
                }).catch(function (e) {
                    reject(e);
                })
            })
        }
    }
    let obj = {
        teacher: "lwj",
        age: 24
    }
    EasyHttp.post("./41.php", obj)
    .then(function (data) {
        console.log(data);
    })
    .catch(function (e) {
        console.log(e);
    });

41.php,

<?php
//echo "it666";

// $teacher = $_GET["teacher"];
// $age = $_GET["age"];
// $arr = array("name"=>$teacher, "age"=>$age);
// $data = json_encode($arr);
// echo $data;

$rws_post = $GLOBALS["HTTP_RAW_POST_DATA"];
$mypost = json_decode($rws_post);
$teacher = (string)$mypost->teacher;
$age = (string)$mypost->age;
$arr = array("name"=>$teacher, "age"=>$age);
$data = json_encode($arr);
echo $data;

?>


二、axios网络请求(常用)

Axios 是一个基于 promise 的 HTTP 库网络请求插件,专注于网络数据请求的库。

相比于原生的 XMLHttpRequest 对象,axios 简单易用

相比于 jQueryaxios 更加轻量化,只专注于网络数据请求。

2.1 axios特点

  • 可以用在浏览器和 node.js 中
  • 支持 Promise API
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF


2.2 GET请求

axios 发起 get 请求的语法:

 axios.get('url', { params: { /*参数*/ } }).then(callback) 

 

示例:

<script src="./axios.js"></script>
    axios.get("./41.php?teacher=lwj&age=20")
        .then(function (res) {
            console.log(res.data);
        })
        .catch(function (e) {
            console.log(e);
        });

41.php,

<?php
//echo "it666";

$teacher = $_GET["teacher"];
$age = $_GET["age"];
$arr = array("name"=>$teacher, "age"=>$age);
$data = json_encode($arr);
echo $data;

?>


2.3 POST请求

 axios 发起 post 请求的语法:

 axios.post('url', { /*参数*/ }).then(callback)

 

示例:

<script src="./axios.js"></script>
    axios.post("./41.php", {
        teacher: "lwj",
        age: 666
    })
        .then(function (res) {
            console.log(res.data);
        })
        .catch(function (e) {
            console.log(e);
        });

41.php,

<?php
//echo "it666";

$rws_post = $GLOBALS["HTTP_RAW_POST_DATA"];
$mypost = json_decode($rws_post);
$teacher = (string)$mypost->teacher;
$age = (string)$mypost->age;
$arr = array("name"=>$teacher, "age"=>$age);
$data = json_encode($arr);
echo $data;

?>


2.4  直接使用axios发起请求

axios 也提供了类似于 jQuery $.ajax() 的函数,语法如下:

 axios({
     method: '请求类型',
     url: '请求的URL地址',
     data: { /* POST数据 */ },
     params: { /* GET参数 */ }
 }) .then(callback)

示例:GET请求

   
 axios({
     method: 'GET',
     url: 'http://www.yyyy',
     params: { // GET 参数要通过 params 属性提供
         name: 'zs',
         age: 20
     }
 }).then(function(res) {
     console.log(res.data)
 })

示例:POST请求

   
 axios({
     method: 'POST',
     url: 'http://www.yyyy',
     data: { // POST 数据要通过 data 属性提供
         bookname: '程序员的自我修养',
         price: 666
     }
 }).then(function(res) {
     console.log(res.data)
 })


2.5 全局的 axios 默认值

在企业开发中项目分为 : 开发阶段和部署阶段, 这两个阶段项目存储的位置是不同的

项目上线前存储在企业内部测试服务器上, 项目上线后存储在企业正式服务器上

所以如果每次请求都将请求的地址写在请求中, 那么项目上线时需要大量修改请求地址

为了解决这个问题, 我们可以配置一个全局URL根地址, 项目上线时只需要修改根地址即可

例如: 上线前地址是: http://127.0.0.1/jQuery/Ajax/41.php

          上线后地址是: http://192.199.13.14/jQuery/Ajax/41.php

    axios.defaults.timeout = 2000; //全局请求超时时间
    axios.defaults.baseURL = "http://127.0.0.1"; // 全局请求根地址
    axios.post("/jQuery/Ajax/41.php", {
        name: "lwj",
        age: 20
    })
        .then(function (res) {
            console.log(res.data);
        })
        .catch(function (e) {
            console.log(e);
        });
<?php
//echo "it666";

$rws_post = $GLOBALS["HTTP_RAW_POST_DATA"];
$mypost = json_decode($rws_post);
$name= (string)$mypost->name;
$age = (string)$mypost->age;
$arr = array("name"=>$name, "age"=>$age);
$data = json_encode($arr);
echo $data;

?>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白小白从不日白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值