In web development, exchanging data between JavaScript and PHP is a common task. This question-and-answer guide addresses how to pass data from JavaScript to PHP and vice versa.
From JavaScript to PHP
To pass data from JavaScript to PHP, you can use XMLHttpRequest to send an asynchronous request to a PHP page. The data can be encoded and sent as a POST or GET request.
From PHP to JavaScript
To pass data from PHP to JavaScript, there are several options:
Implementation
client.js
<code class="javascript">data = {tohex: 4919, sum: [1, 3, 5]}; callPHP(data); function callPHP(params) { // create an XMLHttpRequest object var httpc = new XMLHttpRequest(); // set up the request var url = "server.php"; httpc.open("POST", url, true); // encode the data as a JSON string to send with the request var json = JSON.stringify(params); // send the request httpc.send(json); // handle the response httpc.onreadystatechange = function() { if (httpc.readyState == 4 && httpc.status == 200) { // parse the JSON response var response = JSON.parse(httpc.responseText); // use the response in your JavaScript code } }; }</code>
server.php
<code class="php">$data = json_decode(file_get_contents('php://input'), true); $tohex = $data['tohex']; $sum = array_sum($data['sum']); // calculate and encode the response as a JSON string $response = json_encode([base_convert($tohex, 16), $sum]); // echo the response echo $response;</code>
The above is the detailed content of How to Effectively Exchange Data Between JavaScript and PHP?. For more information, please follow other related articles on the PHP Chinese website!