mirror of
https://gitee.com/many2many/java-web.git
synced 2025-01-11 14:40:55 +08:00
59 lines
2.1 KiB
JavaScript
59 lines
2.1 KiB
JavaScript
|
$(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>`);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
});
|