0
点赞
收藏
分享

微信扫一扫

发送带有参数的get,post请求

Brose 2022-04-05 阅读 60

    <script>

      /*

        发送带有参数的get请求

        ==>GET请求就是直接在地址栏后面拼接queryString方式携带参数

        ==>open的第二个参数就是请求地址

        ==>把要携带给后端的内容通过open的第二个参数携带过去

        发送带有参数的post请求

        ==>POST携带参数在请求体,不需要在地址栏拼接

            =>数据格式无所谓,但是要和content-type配套

        ==>send()在括号里面的就是请求体

        ==>没有设置content-type后端不能正常按照$_POST的方式解析

            =>需要设置请求头,content-type设置为application/x-www-form-urlencoded  

            =>语法:xhr.setRequestHeader(key,value)      

       

        */

      /* GET

      //创建一个ajax实例化对象

      const xhr = new XMLHttpRequest();

      //2、配置本次请求信息

      xhr.open("GET", "get1.php?a=100&b=200");

      //3、把这个请求发送出去

      xhr.send();

      //接受结果

      xhr.onload = function () {

        console.log(JSON.parse(xhr.responseText));

      }; */

      //POST

      //创建一个ajax实例化对象

      const xhr = new XMLHttpRequest();

      //2、配置本次请求信息

      xhr.open("POST", "post.php");

      //接受结果

      xhr.onload = function () {

        console.log(JSON.parse(xhr.responseText));

      };

      //post请求需要在请求之前设置请求头

      xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");

      //3、把这个请求发送出去

      xhr.send("a=100&b=200");

    </script>

//GET.PHP

<?php

//组装一个数组

$arr = array(

    "message" => "接受GET成功,参数原样返回",

    "date" => $_GET

);

echo json_encode($arr);

?>

//POST.PHP

<?php

//组装一个数组

$arr = array(

    "message" => "接受POST成功,参数原样返回",

    "date" => $_POST

);

echo json_encode($arr);

?>

举报

相关推荐

0 条评论