java-web/examples/chapter03/jquery-app.js

59 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2024-08-07 23:24:00 +08:00
$(document).ready(function() {
// GET 请求按钮
$('#getButton').on('click', function() {
$.getJSON('https://jsonplaceholder.typicode.com/posts')
.done(function(data) {
displayResults('#getResults', data);
})
.fail(function(error) {
console.error('Error fetching data:', error);
displayResults('#getResults', { error: 'An error occurred while fetching data.' });
});
});
// POST 请求表单
$('#postForm').on('submit', function(event) {
event.preventDefault();
const title = $('#title').val();
const body = $('#body').val();
const userId = $('#userId').val();
const postData = {
title: title,
body: body,
userId: userId
};
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'POST',
data: JSON.stringify(postData),
contentType: 'application/json; charset=UTF-8',
success: function(data) {
displayResults('#postResults', data);
},
error: function(error) {
console.error('Error posting data:', error);
displayResults('#postResults', { error: 'An error occurred while posting data.' });
}
});
});
// 显示结果的函数
function displayResults(selector, data) {
$(selector + ' .card-text').empty();
if (Array.isArray(data)) {
data.forEach(item => {
$(selector + ' .card-text').append(`ID: ${item.id}<br>`);
$(selector + ' .card-text').append(`Title: ${item.title}<br>`);
$(selector + ' .card-text').append(`Body: ${item.body}<br>`);
$(selector + ' .card-text').append(`User ID: ${item.userId}<br>`);
$(selector + ' .card-text').append('<hr>');
});
} else {
for (let key in data) {
$(selector + ' .card-text').append(`${key}: ${data[key]}<br>`);
}
}
}
});