Home > Article > Web Front-end > Detailed explanation of how to use fetch and how to receive JS values
This article mainly introduces the use of fetch and how to receive JS values. The article mentions the basic usage of fetch and the use of receiving JS values. Friends who need it can refer to it. I hope it can help everyone.
Basic method of using 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) })
Method 1: Add headers definition
The headers are defined as follows:
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
At the same time, the body value is passed as follows Method:
body:'username='+uname+'&password='+password
Use the following reception in php
input('username')
Method 2: Change the reception method in php
The reception method is as follows:
$arr = file_get_contents("php://input");
Return string Object, the following processing needs to be done to use the value:
$result=array(); foreach (explode('&', $arr) as $t){ list($a,$b)=explode('=', $t); $result[$a]=$b; }
At this time, you can receive the passed value as follows:
$result['username']
Related recommendations:
How to solve the preflight request encountered after adding header in the fetch method
Example of how JavaScript uses fetch to complete asynchronous requests introduce
The above is the detailed content of Detailed explanation of how to use fetch and how to receive JS values. For more information, please follow other related articles on the PHP Chinese website!