$(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}
`); $(selector + ' .card-text').append(`Title: ${item.title}
`); $(selector + ' .card-text').append(`Body: ${item.body}
`); $(selector + ' .card-text').append(`User ID: ${item.userId}
`); $(selector + ' .card-text').append('
'); }); } else { for (let key in data) { $(selector + ' .card-text').append(`${key}: ${data[key]}
`); } } } });