html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="ajax.js"></script>
</head>
<body>
</body>
</html>
ajax.js
'use strict';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
var x = JSON.parse(xhr.responseText);
console.log(typeof x);
console.log(x.mycode);
} else {
console.log(xhr.status);
}
}
}
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");
xhr.send(JSON.stringify({"id":1}));
server.php
<?php
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$id = $request->id;
echo json_encode([
"mycode" => $id
]);
}
?>
南无阿弥陀佛,善哉善哉