[英]how to convert the JSON object into form data and send it as Data to web api fetch
[英]How To Send A Data Object With Fetch API
我想發送一個數據object with fetch api with keepalive到當前頁面,通過php獲取數據,請問如何實現。
要發送的數據
{
name: 'blabla',
age: 432,
type: 'pig'
}
我想作為一個后變量接收
$_POST['name'];
我已經試過了,但沒有用
fetch('', {
method: 'POST',
body: {name: 'blabla'},
keepalive: true
});
抱歉沒有代碼
不知道 keepalive 是什么,但如果我想向 php 后端發送獲取請求,我通常會這樣做:
fetch("backend.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: "data=" + data,
})
.then((response) => response.json())
.then((response) => doWhatYouWant(response))
.catch((error) => alert("Error : " + error));
您可以使用 json 作為內容類型調用 fetch 並使用方法 POST 正如您已經嘗試過的那樣,您還必須序列化正文中的內容
fetch("backend.php", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "blablabla" }),
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.