鍍金池/ 問答/PHP  HTML/ 后端如何接收fetch方式發(fā)送的數(shù)據(jù)?

后端如何接收fetch方式發(fā)送的數(shù)據(jù)?

fetch方法借助FormData對象模擬表單的請求

這樣能夠?qū)崿F(xiàn)完整的HTTP請求,而后端也能夠像表單樣接收數(shù)據(jù)

//前端
var formdata = new FormData();
formdata.append('username','lofayo');
fetch('web.php',{
    method: 'POST',
    body:formdata
})
.then(res=>res.text())
.then(resTxt=>console.log(resTxt))

//后端
//web.php
$username = $_POST['username']

fetch方式的post請求,數(shù)據(jù)還是模擬表單。可是,若像fetch官網(wǎng),直接這樣提交數(shù)據(jù),那后臺如何接收?

就是不似表單形式,而是字符串,那后臺程序又該如何接收?

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
回答
編輯回答
貓小柒

后端打印下 $_POST,看下數(shù)據(jù)格式不就知道了

2018年9月1日 19:20
編輯回答
詆毀你
$data = json_decode(file_get_contents('php://input'),true);
print_r($data);
2018年3月25日 10:01