使用fetch基本方式:
fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({ username: 'username', password: 'password'}) }).then(function(res){ console.log(res) })方式一:增加headers 定義
在headers頭部定義如下:
headers: {'Content-Type': 'application/x-www-form-urlencoded'},同時body傳值使用如下方式:
body:'username='+uname+'&password='+password
在php中使用如下接收
input('username')方式二:改變php中接受方式
接受方式如下:
$arr = file_get_contents("php://input");返回字符串對象,使用值需要做如下處理:
$result=array(); foreach (explode('&', $arr) as $t){ list($a,$b)=explode('=', $t); $result[$a]=$b; }此時便可以如下接收傳值:
$result['username']
總結
以上所述是小編給大家介紹的fetch 使用及如何接收JS傳值,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答