问题
I am trying to use fetch()
API POST method in order to grab the POST data in PHP.
Here is what I have tried:
var x = "hello";
fetch(url,{method:'post',body:x}).then(function(response){
return response.json();
});
PHP:
<?php
if(isset($_GET['x']))
{
$get = $_GET['x'];
echo $get;
}
?>
Is this correct?
回答1:
It depends:
If you want to $_GET['x']
, you need to send the data in the querystring:
var url = '/your/url?x=hello';
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (body) {
console.log(body);
});
If you want to $_POST['x']
, you need to send the data as FormData
:
var url = '/your/url';
var formData = new FormData();
formData.append('x', 'hello');
fetch(url, { method: 'POST', body: formData })
.then(function (response) {
return response.text();
})
.then(function (body) {
console.log(body);
});
回答2:
Appearently, when using the Fetch API to send data to a PHP server, you'll have to handle the request a little different from what you're used to.
The data you're "POSTing" or "GETting" is not going to be available in the super global variables since this input is not coming from a multipart-data form or an application/x-www-form-urlencoded
You can get your data by reading the special file: php://input
, for example using file_get_contents('php://input')
and then try to decode that input with json_decode()
.
Hopefully it helps.
You cand read more about it here:
https://codepen.io/dericksozo/post/fetch-api-json-php
回答3:
I use the postData function from MDN:
/**
* send_body___receive_response.js
*
* Can of-course be in <script> tags in HTML or PHP
*/
async function postData( url='', data={ } ) {
// *starred options in comments are default values
const response = await fetch(
url,
{
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json", // sent request
"Accept": "application/json" // expected data sent back
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify( data ), // body data type must match "Content-Type" header
},
);
return response.json( ); // parses JSON response into native JavaScript objects
}
const data = {
'key1': 'value1',
'key2': 'value2'
};
postData( 'receive_body___send_response.php', JSON.stringify( data ) )
.then( response => {
// Manipulate response here
console.log( "response: ", response ); // JSON data parsed by `data.json()` call
// In this case where I send entire $decoded from PHP you could arbitrarily use this
console.log( "response.data: ", JSON.parse( response.data ) );
} );
You could just POST data but I like to receive a response that it was successful.
/**
* receive_body___send_response.php
*/
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
// Set initial response
$response = [
'value' => 0,
'error' => 'Nothing happened',
'data' => null,
];
if ($contentType === "application/json") {
// Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
// $decoded can be used the same as you would use $_POST in $.ajax
$decoded = json_decode($content, true);
if(! is_array($decoded)) {
// NOTE: Sometimes for some reason I have to add the next line as well
/* $decoded = json_decode($decoded, true); */
// Do something with received data and include it in reponse
/* perhaps database manipulation here */
$response['data'] = $decoded;
// Success
$response['value'] = 1;
$response['error'] = null;
} else {
// The JSON is invalid.
$response['error'] = 'Received JSON is improperly formatted';
}
} else {
// Content-Type is incorrect
$response['error'] = 'Content-Type is not set as "application/json"';
}
// echo response for fetch API
echo json_encode($response);
来源:https://stackoverflow.com/questions/33439030/how-to-grab-data-using-fetch-api-post-method-in-php