java-web/examples/chapter03/jquery.html

65 lines
2.0 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div>
<h2 id="title"></h2>
<div id="content"></div>
</div>
<div>
<h2 id="title2"></h2>
<div id="content2"></div>
</div>
</body>
<script>
let url = 'https://jsonplaceholder.typicode.com/posts/1';
$.get(url, function(data, textStatus, jqXHR) {
console.log('Data received:', data);
console.log('Text Status:', textStatus);
console.log('jqXHR:', jqXHR);
$("#title").html(data.title);
$("#content").html(data.body);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error('Request failed:', textStatus, errorThrown);
});
// 或者使用 $.ajax() 方法发送 GET 请求
$.ajax({
url: url,
type: 'GET',
success: function(data, textStatus, jqXHR) {
console.log('Data received:', data);
console.log('Text Status:', textStatus);
console.log('jqXHR:', jqXHR);
$("#title2").html(data.title);
$("#content2").html(data.body);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Request failed:', textStatus, errorThrown);
}
});
//发送 POST 请求
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'POST',
data: { title: 'axjax入门', body: 'abcdefghijklmn', userId: 1 }, // 附加数据
contentType: 'application/x-www-form-urlencoded', // 默认值,可以省略
success: function(data, textStatus, jqXHR) {
console.log('Post Data received:', data);
console.log('Post Text Status:', textStatus);
console.log('Post jqXHR:', jqXHR);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Post failed:', textStatus, errorThrown);
}
});
</script>
</html>