问题:
<div id="show"></div>
<input type="button" id="btn" value="请求数据" />
要求:当点击ID为btn的按钮后,向text.jsp发送一个异步请求,请求参数为"company=sinora,department=webdesign",并将响应数据显示ID为show的div中
答案:
因为text.jsp是一个虚拟的接口路径,所以会报请求失败
<!DOCTYPE html>
<html>
<head>
<title>Ajax请求示例</title>
<style>
#show {
width: 300px;
height: 300px;
border: 1px solid #000;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div id="show"></div>
<input type="button" id="btn" value="请求数据" @click="requestData" />
<script>
$(document).ready(function(){
$("#btn").click(function(){
// 定义请求参数
var requestData = {
company: "soora",
department: "webdesign"
};
// 发送Ajax请求
$.ajax({
type: "GET", // 请求类型
url: "text.jsp", // 请求地址
data: requestData, // 请求参数
success: function(response){
// 请求成功时的回调函数
$("#show").html(response); // 将响应数据显示在id为show的div中
},
error: function(){
// 请求失败时的回调函数
alert("请求失败");
}
});
});
});
</script>
</body>
</html>