一)使用原生JS实现Ajax请求
这是请求页面
<!DOCTYPE html>
<html>
<head>
<title>使用原生JS实现Ajax请求</title>
</head>
<body>
<button id="getData">Get Data</button>
<div id="result"></div>
<script>
result = document.getElementById('result');
document.getElementById('getData').onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'Ajax.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);//将json数据转成对象
result.innerHTML = "Name: " + response.name + ", Age: " + response.age;
}
};
xhr.send();
}
</script>
</body>
</html>
这是处理页面
<?php
$data = array("name" => "john", "age" => 30);
echo json_encode($data);
?>
二)使用jQuery库实现Ajax请求
这是请求页面
<!DOCTYPE html>
<html>
<head>
<title>使用jQuery库实现Ajax请求</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#getData").click(function(){
$.ajax({
url: "Ajax.php",
type: "GET",
datatype:"json",
success: function(response){
// 解析返回的JSON数据
var data = JSON.parse(response); //将json数据转成对象
$("#result").html("Name: " + data.name + ", Age: " + data.age);
}
});
});
});
</script>
</head>
<body>
<button id="getData">Get Data</button>
<div id="result"></div>
</body>
</html>
处理页面同上。