fetch测试用get方法发送数据和获取后端数据

前端fetchget.html把我们想要发送的数据以get的形式发到后端;
如:foo=bar&baz=que格式的数据发送给后端

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
        <title>测试fetch的get用法</title>
    </head>
    <body>
        <script type="text/javascript">
        //第一个参数为URL,第二个参数为init的对象
            fetch('fetchget.php?foo=bar&baz=qux',{
                modth:"get",//发送模式
                headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF8'}//设置发送标头
            }).then(response=>{
            //这里期约返回response,再检查response的ok,status属性是否是真
                if(response.ok && response.status===200)
                {
                //response.json()方法转换为json格式;获取他的实例是data
                //response.blob()实例为blob;response.text()实例为data
                    return response.json();
                }
                throw new Error('Network response was not ok.');
            }).then(data=>{
                //这里是response.json()方法的实例,实例就是返回的数据
                console.log(data.data.foo);
            }).catch(error=>{
                console.log('提取数据发生错误:',error);
            });
        </script>
    </body>
</html>

//这里是后端处理数据和返回数据

<?php
//检查获取模式是否为get
if($_SERVER['REQUEST_METHOD']==='GET')
{
//获取前端的值
    $foo=$_GET['foo'];
    $baz=$_GET['baz'];
    if(isset($foo)&&isset($baz))
    {
    //把要返回的值集中到数组中
        $data=[
            'message'=>'hello world',
            'timestamp'=>date('Y-m-d H:i:s'),
            'data'=>['foo'=>$foo,'baz'=>$baz]
        ];
    }
    //设置标头为json格式
    header('Content-Type:application/json');
    //返回数据
    echo json_encode($data);
    
}else
{
//如果不是get模式,则返回错误信息
    header('HTTP/1.1 405 Method Not Allowed');
    echo json_encode(['error'=>'Method Not Allowed']);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值