Home > Web Front-end > JS Tutorial > Communication between PHP and js (via ajax, json)_javascript skills

Communication between PHP and js (via ajax, json)_javascript skills

WBOY
Release: 2016-05-16 18:16:18
Original
1020 people have browsed it
JavaScript side:
Note: xmlHttp.setRequestHeader must be set, otherwise the parameters passed to PHP will become null (line 38)
The highlight is line 31!
Copy code The code is as follows:


< ;input type="button" onclick="GetJson()" value="Click me! "/>




PHP [testJson.php] :
(Note that the php file must be clean, and there cannot be other tags outside the tag, otherwise the eval function cannot parse)
The highlight is line 6
Copy code The code is as follows:

$res['id'] = $_POST[' id'];
$res['name'] = "elar";
$res['age'] = "21";
$response = "hello this is response".$_POST[ 'id'];
echo json_encode($res);
?>

Summary:
js needs to send data to PHP, using xmlHttp.send( "id=123");
PHP sends data to js, ​​using echo json_encode($res); (note that the construction of the variable $res should comply with JSON specifications)
js needs to parse the data sent by PHP For data in JSON format, use var obj = eval('(' xmlHttp.responseText ')');
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template