JavaScript side:
Note: xmlHttp.setRequestHeader must be set, otherwise the parameters passed to PHP will become null (line 38)
The highlight is line 31!
< ;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
$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 ')');