欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

详解fetch的使用方法及如何接收JS传值

程序员文章站 2022-03-21 12:25:43
...
本文主和要介绍了fetch 使用及如何接收JS传值,文中给大家提到了fetch基本使用方式和接收js传值的使用方式,需要的朋友可以参考下,希望能帮助到大家。

使用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']

相关推荐:

php中的四个fetch语句

如何解决在fetch方法中添加header后遇到的预检请求

JavaScript如何使用fetch来完成异步请求的实例介绍

以上就是详解fetch的使用方法及如何接收JS传值的详细内容,更多请关注其它相关文章!