17.传统ajax与fetch
2020-05-21 本文已影响0人
web_jianshu
<!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="Jerry" /> 密码:
<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());
})
.catch(async err => {
// throw await err;
console.log(await err);
});
// =================第一种结束==================
// ===================第二种===================
// 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());
// })
// .catch(async err => {
// console.log(await err);
// });
// ====================第二种结束===============
// =====================第三种==================
// 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());
// })
// .catch(async err => {
// console.log(await err);
// });
// ==================第三种结束===================
// ==================GET===================
// fetch(
// `./receive.php?username=${username.value}&password=${password.value}`,
// {
// method: "GET"
// }
// )
// .then(res => {
// return res.text();
// })
// .then(text => {
// console.log(JSON.parse(text));
// })
// .catch(err => {
// console.log(err);
// });
});
</script>
</body>
</html>
- receive.php 内容如下 =>
<?php
// 第一种
echo json_encode($_POST);
// 第二种
// echo json_encode($_POST);
// 第三种
// echo file_get_contents("php://input");
// GET
// echo json_encode($_GET);