我使用MDN的 postData 函数:
/**
* 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': 2
};
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 ) );
} );
您可以只发布数据,但我希望收到成功的响应。
/**
* receive_body___send_response.php
*/
/* Get content type */
$contentType = trim($_SERVER["CONTENT_TYPE"] ?? ''); // PHP 8+
// Otherwise:
// $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
/* Send error to Fetch API, if unexpected content type */
if ($contentType !== "application/json")
die(json_encode([
'value' => 0,
'error' => 'Content-Type is not set as "application/json"',
'data' => null,
]));
/* 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);
/* Send error to Fetch API, if JSON is broken */
if(! is_array($decoded))
die(json_encode([
'value' => 0,
'error' => 'Received JSON is improperly formatted',
'data' => null,
]));
/* NOTE: For some reason I had to add the next line as well at times, but it hadn't happen for a while now. Not sure what went on */
// $decoded = json_decode($decoded, true);
/* Do something with received data and include it in response */
// dumb e.g.
$response = $decoded['key2'] + 1; // 3
/* Perhaps database manipulation here? */
// query, etc.
/* Send success to fetch API */
die(json_encode([
'value' => 1,
'error' => null,
'data' => null, // or ?array of data ($response) you wish to send back to JS
]));