Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to use fetch and how to receive JS values

小云云
Release: 2017-12-22 10:41:30
Original
3653 people have browsed it

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)
 })
Copy after login

Method 1: Add headers definition

The headers are defined as follows:

headers: {'Content-Type': 'application/x-www-form-urlencoded'},
Copy after login

At the same time, the body value is passed as follows Method:

body:'username='+uname+'&password='+password
Copy after login

Use the following reception in php

input('username')
Copy after login

Method 2: Change the reception method in php

The reception method is as follows:

$arr = file_get_contents("php://input");
Copy after login

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;
 }
Copy after login

At this time, you can receive the passed value as follows:

$result['username']
Copy after login

Related recommendations:

Four fetch in php Statement

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template