fetch发送请求

fetch发送请求

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>Test Page</h1>
    用户名: <input type="text" name="username" id="username" value="123">
    密码: <input type="password" name="password" id="password" value="321">
    <input type="submit" value="Submit" id='btn'>
    <script>
        let submitBtn = document.querySelector('#btn')
        let username = document.querySelector('#username')
        let password = document.querySelector('#password')
        submitBtn.addEventListener('click', () => {
            let formData = new FormData()
            formData.append('username', username.value)
            formData.append('password', password.value)
           
            // ================第一种======================
            /*fetch('./receive.php', {
                method: 'POST',
                body: formData
            }).then(async (res)=>{
                console.log(await res.json())
            })
            */
            /*
            	receive.php文件
                echo json_encode($_POST);
            */ 
            // =================第一种结束==================
            
            // ===================第二种===================
            /* fetch('./receive.php', {
                method: 'POST',
                headers: {
                    'Content-type': 'application/x-www-form-urlencoded'
                },
                body: `username=${username.value}&password=${password.value}`
            }).then(async (res) => {
                console.log(await res.json())
            }) */
            /*
            	receive.php文件
                echo json_encode($_POST);
            */ 
            // ====================第二种结束===============
            
            // =====================第三种==================
            
             fetch('./receive.php', {
                method: 'POST',
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    username: username.value,
                    password: password.value
                })
            }).then(async (res) => {
                console.log(await res.json())
            })
             /*
            	receive.php文件
                echo file_get_contents("php://input");
            */ 
            // ==================第三种结束===================
            
        })
    </script>
</body>

</html>

发布了39 篇原创文章 · 获赞 2 · 访问量 572

猜你喜欢

转载自blog.csdn.net/qq_39583550/article/details/104629886