封装Ajax

时间:2022-09-01 01:29:22


封装get方法

<!--
 * @Date: 2023-04-06 09:40:41
 * @LastEditors: Mei
 * @LastEditTime: 2023-04-06 09:57:40
 * @FilePath: \vscode\ajax_get.html
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="sendMsg()">发送请求</button>

    <script>
        function sendMsg(){
            get('./data.php',{id:2,title:"mez"},function(resp){
                console.log(resp)
            },true)
        }
        //封装get
        //url:string,请求的地址
        //query:object ,请求懈怠的参数
        //callback  成功之后的回调

        //isJson:boolean,是否需要解析JSON
        function get(url,query,callback,isJson){

            //如果有参数,先把参数拼接在url后面
            if(query){
                url+='?'
                for (var key in query){
                    url+=`${key}=${query[key]}&`
                }
                //去除最后多于的&
                url=url.slice(0,-1)
            }
            var xhr=new XMLHttpRequest()
            xhr.open('get',url)
            xhr.send()
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    if(xhr.status===200){
                        var res=isJson? JSON.parse(xhr.responseText):xhr.responseText
                        callback(res)
                    }
                }
            }


        }
    </script>
</body>
</html>

测试用的PHP文件

<?php
/*
 * @Date: 2023-04-06 09:49:43
 * @LastEditors: Mei
 * @LastEditTime: 2023-04-06 09:55:13
 * @FilePath: \vscode\data.php
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
 */

$id =$_GET['id'];
$title=$_GET['title'];
// echo 'hello get';
echo json_encode(array(
    'id'=>$id
    'title'=>$title
    'age'=>19
))
?>

封装post方法

<!--
 * @Date: 2023-04-06 09:40:41
 * @LastEditors: Mei
 * @LastEditTime: 2023-04-06 10:07:50
 * @FilePath: \vscode\ajax_post.html
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="sendMsg()">发送请求</button>

    <script>
        function sendMsg(){
            // get('./data.php',{id:2,title:"mez"},function(resp){
            //     console.log(resp)
            // },true)
            post('./data.php',{id:2,title:"mez"},function(resp){
                console.log(resp)
            },true)
        }
        //封装get
        //url:string,请求的地址
        //query:object ,请求懈怠的参数
        //callback  成功之后的回调

        //isJson:boolean,是否需要解析JSON
        function post(url,query,callback,isJson){
            var str=''
            //如果有参数,先把参数拼接起来
            if(query){
                // url+='?'
                for (var key in query){
                    str+=`${key}=${query[key]}&`
                }
                //去除最后多于的&
                str=str.slice(0,-1)
            }
            var xhr=new XMLHttpRequest()
            xhr.open('post',url)
            xhr.setRequestHeader('content-Type','application/x-www-form-urlencoded')
            xhr.send(str)
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    if(xhr.status===200){
                        var res=isJson? JSON.parse(xhr.responseText):xhr.responseText
                        callback(res)
                    }
                }
            }


        }
    </script>
</body>
</html>

对应的PHP文件

<?php
/*
 * @Date: 2023-04-06 09:49:43
 * @LastEditors: Mei
 * @LastEditTime: 2023-04-06 10:07:31
 * @FilePath: \vscode\data.php
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
 */

$id =$_POST['id'];
$title=$_POST['title'];
// echo 'hello get';
echo json_encode(array(
    'id'=>$id
    'title'=>$title
    'age'=>19
))
?>