-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
60 lines (55 loc) · 1.84 KB
/
Copy pathscript.js
File metadata and controls
60 lines (55 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
document.getElementById('postForm').addEventListener('submit', function(event) {
event.preventDefault();
const title = document.getElementById('title').value;
const content = document.getElementById('content').value;
if (!title || !content) {
alert('Please fill in both fields');
return;
}
const post = { title, content };
fetch('http://127.0.0.1:5000/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(post)
})
.then(response => response.json())
.then(data => {
document.getElementById('title').value = '';
document.getElementById('content').value = '';
loadPosts();
})
.catch(error => console.error('Error creating post:', error));
});
function loadPosts() {
fetch('http://127.0.0.1:5000/posts')
.then(response => response.json())
.then(data => {
posts = data;
displayPosts();
})
.catch(error => console.error('Error loading posts:', error));
}
function displayPosts() {
const postsContainer = document.getElementById('posts');
postsContainer.innerHTML = '';
posts.forEach(post => {
const postElement = document.createElement('div');
postElement.className = 'post';
postElement.innerHTML = `
<h3>${post.title}</h3>
<p>${post.content}</p>
<button onclick="deletePost(${post.id})">Delete</button>
`;
postsContainer.appendChild(postElement);
});
}
function deletePost(id) {
fetch(`http://127.0.0.1:5000/posts/${id}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
loadPosts();
})
.catch(error => console.error('Error deleting post:', error));
}