这是学校的作业。我用express创建了一个服务器,并用jquery创建了一个应用。它不是在使用数据库,而是在文件中写入json。
就像Twitter,但它被称为Chirper,每个html段落都像一条推文,但被称为“ chirp”。我为每个向服务器发送ajax删除请求的线性调频脉冲创建了一个删除按钮。该按钮在某些chi声上起作用,但在其他chi声上不起作用。通过工作,我的意思是从json文件中删除了json chirp。导致每个删除按钮无法正常工作的错误是什么?
我首先在这里复制了我的app.js文件:
$(document).ready(function () {
let chirps = [];
let user;
let text;
// handle API request (api call below) the server responds with a nested object of chirps
function handleResponse(data) {
// change object into array of objects
let entries = Object.entries(data)
// destructure entries array & extract user & text to chirps array
for (const [number, chirp] of entries) {
chirps.push(`${chirp.user}: ${chirp.text}`);
}
// remove 'nextid' element in array
chirps.pop();
// map over array,
chirps.map((chirp, index) => {
// get a timestamp for each chirp
let time = (new Date().getTime())
// create a delete button for each chirp, set class
let x = $('<button>x</button>').attr('class', 'delete');
// create a paragraph containing each chirp
let p = $(`<p>${chirp}</p>`).attr({
// set a class for styling
class: "chirps",
// set a timestamp key (referenced by 'id' in server methods) for deleting/updating later
key: `${time}`
}).append(x);
// append each paragraph to div
$('.current').append(p)
})
}
// use get request to call api
$.get('http://127.0.0.1:3000/api/chirps').then(handleResponse).catch(err => console.log(err)); // or use localhost:3000
// on submit button click, get the value of user inputs and ...
$('#submit').click(() => {
user = $('#user').val();
text = $('#text').val();
// make a post request with those values
$.ajax({
type: "POST",
url: 'http://127.0.0.1:3000/api/chirps/',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "user": `${user}`, "text": `${text}` })
})
.catch(err => console.log(err));
})
// on delete button click
$(document).on("click", ".delete", event => {
// set variable for the button's parent (the chirp)
let chirpToDelete = $(event.target).parent()
// remove html chirp from display
chirpToDelete.remove()
// also send delete request to remove from server
$.ajax({
type: "DELETE",
url: `http://127.0.0.1:3000/api/chirps/${chirpToDelete.attr('key')}`
})
.then(() => console.log(`deleted chirp ${chirpToDelete.attr('key')}`))
.catch(err => console.log(err))
})
})
接下来是我的server.js文件:
const fs = require('fs'); // import file system
let chirps = { nextid: 0 }; // keep track of chirps
if(fs.existsSync('chirps.json')) { // check for existing chirps file
chirps = JSON.parse(fs.readFileSync('chirps.json')); // if already there, read the file and set chirps count to that file
}
let getChirps = () => { // calling getChirps will return all the chirps
return Object.assign({}, chirps); // Object.assign creates a copy to send back to protect from manipulation
}
let getChirp = id => { // getChirp with id returns copy of one specfic chirp
return Object.assign({}, chirps[id]);
}
let createChirp = (chirp) => { // createChirp creates a chirp with next available id
chirps[chirps.nextid++] = chirp; // saved in chirps object
writeChirps(); // call function to write the chirp (below)
};
let updateChirp = (id, chirp) => { // pass in id & chirp to update existing
chirps[id] = chirp;
writeChirps();
}
let deleteChirp = id => { // delete a chirp with specific id
delete chirps[id];
writeChirps();
}
let writeChirps = () => { // chirps written to json
fs.writeFileSync('chirps.json', JSON.stringify(chirps));
};
module.exports = { // export each (no need to export writeChirps because it is for this file only)
CreateChirp: createChirp,
DeleteChirp: deleteChirp,
GetChirps: getChirps,
GetChirp: getChirp,
UpdateChirp: updateChirp
}
答案 0 :(得分:0)
$(document).ready(function () {
let chirps = [];
let user;
let text;
// handle API request (api call below) the server responds with a nested object of chirps
function handleResponse(data) {
// change object into array of objects for iteration
let entries = Object.entries(data)
// destructure entries array & extract user, text in an object to chirps array
for (const [id, data] of entries) {
chirps.push({
"user": `${data.user}`,
"text": `${data.text}`,
"id": `${id}`
});
}
// remove 'nextid' element in array
chirps.pop();
// map over array, for each object in the array ...
chirps.map(chirp => {
// create a delete button for each chirp, set class
let x = $('<button>x</button>').attr('class', 'delete');
// create a paragraph containing each chirp, set a class for styling, set id with timestamp, append a delete button to each paragraph
let p = $(`<p>${chirp.user}: ${chirp.text}</p>`).attr({
class: "chirps",
id: `${chirp.id}`
}).append(x);
// append each paragraph to div
$('.current').append(p)
})
}
// use get request to call api
$.get('http://127.0.0.1:3000/api/chirps').then(handleResponse).catch(err => console.log(err)); // or use localhost:3000
// on submit button click, get the value of user inputs and ...
$('#submit').click(() => {
user = $('#user').val();
text = $('#text').val();
// make a post request with those values
$.ajax({
type: "POST",
url: 'http://127.0.0.1:3000/api/chirps/',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"user": `${user}`,
"text": `${text}`,
})
})
.catch(err => console.log(err));
})
// on delete button click
$(document).on("click", ".delete", event => {
// set variable for the button's parent (the chirp)
let chirpToDelete = $(event.target).parent()
// remove html chirp from display
chirpToDelete.remove()
// also send delete request to remove from server
$.ajax({
type: "DELETE",
url: `http://122.0.0.1:3000/api/chirps/${chirpToDelete.attr('id')}`
})
.catch(err => console.log(err))
})
})