全国统一服务热线:400-633-9193

fetch 使用及如何接收JS传值

    网络     2017-11-17    1241

使用fetch基本方式:

1
2
3
4
5
6
7
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头部定义如下:

1
headers: {'Content-Type': 'application/x-www-form-urlencoded'},

同时body传值使用如下方式:

1
body:'username='+uname+'&password='+password

在php中使用如下接收

1
input('username')

方式二:改变php中接受方式

接受方式如下:

1
$arr = file_get_contents("php://input");

返回字符串对象,使用值需要做如下处理:

1
2
3
4
5
$result=array();
 foreach (explode('&', $arr) as $t){
 list($a,$b)=explode('=', $t);
 $result[$a]=$b;
 }

此时便可以如下接收传值:

1
$result['username']


  分享到:  
0.1753s