document.addEventListener('DOMContentLoaded', function() {
// GET 请求按钮
const getButton = document.getElementById('getButton');
// 显示 GET 请求结果的区域
const getResults = document.getElementById('getResults');
// POST 请求表单
const postForm = document.getElementById('postForm');
// 显示 POST 请求结果的区域
const postResults = document.getElementById('postResults');
// GET 请求函数
getButton.addEventListener('click', function() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
displayResults(getResults, data);
})
.catch(error => {
console.error('Error fetching data:', error);
displayResults(getResults, { error: 'An error occurred while fetching data.' });
});
});
// POST 请求函数
postForm.addEventListener('submit', function(event) {
event.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
const userId = document.getElementById('userId').value;
const postData = {
title: title,
body: body,
userId: userId
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(postData),
})
.then(response => response.json())
.then(data => {
displayResults(postResults, data);
})
.catch(error => {
console.error('Error posting data:', error);
displayResults(postResults, { error: 'An error occurred while posting data.' });
});
});
// 显示结果的函数
function displayResults(element, data) {
element.querySelector('.card-text').textContent = '';
if (Array.isArray(data)) {
data.forEach(item => {
element.querySelector('.card-text').appendChild(document.createTextNode(`ID: ${item.id}
`));
element.querySelector('.card-text').appendChild(document.createTextNode(`Title: ${item.title}
`));
element.querySelector('.card-text').appendChild(document.createTextNode(`Body: ${item.body}
`));
element.querySelector('.card-text').appendChild(document.createTextNode(`User ID: ${item.userId}
`));
element.querySelector('.card-text').appendChild(document.createElement('hr'));
});
} else {
for (let key in data) {
element.querySelector('.card-text').appendChild(document.createTextNode(`${key}: ${data[key]}
`));
}
}
}
});