PHP può supportare richieste POST in JSON adottando una semplice strategia.
Supponiamo di avere questo tipo di richiesta in JavaScript:
'use strict';
const postData = (url = '', data = {}) => {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
};
L'array globale $_POST
in questo caso è vuoto e quindi dobbiamo usare lo stream di input.
<?php
header('Content-Type: application/json');
$post_data = json_decode(file_get_contents('php://input'), true);
$output = [];
$output['text'] = $post_data['test'];
echo json_encode($output);
exit;
?>