Parsing JSON Data from Javascript to PHP
Sending JSON data from Javascript in the browser to a server and having it parsed in PHP entails several steps.
1. Creating the JSON String
In Javascript, use the JSON.stringify() method to convert an object to a JSON string. This string will contain the data to be sent to the server.
2. Sending the JSON Data with AJAX
Utilize Javascript's XMLHttpRequest object to establish an AJAX connection to the server. Set the Content-type header to either:
3. Parsing the JSON Data in PHP
If you used the "application/json" header, read the raw POST data using:
$str_json = file_get_contents('php://input');
If you used the "application/x-www-form-urlencoded" header, access the data via $_POST, but remember to first create a POST string in Javascript. Decode the JSON string using json_decode().
Pitfalls to Avoid
References
The above is the detailed content of How to Parse JSON Data from JavaScript to PHP?. For more information, please follow other related articles on the PHP Chinese website!