javascript - jquery ajax删除请求删除一些但不是全部
问题描述
这是学校的作业。我用 express 创建了一个服务器,用 jquery 创建了一个应用程序。它不是使用数据库,而是将 jsons 写入文件。
它就像 Twitter,但它被称为 Chirper,每个 html 段落就像一条推文,但被称为“chirp”。我为每个向服务器发送 ajax 删除请求的啁啾创建了一个删除按钮。该按钮适用于某些啁啾,但不适用于其他啁啾。通过工作,我的意思是从 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
}
解决方案
$(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))
})
})
推荐阅读
- c++ - 无法从向量返回指针
- kubernetes - 无法在 Pod 中挂载本地目录
- java - 弹簧执行器“/auditevents”端点返回 404
- lua - Lua:未使用“math.random”生成的值
- python - Pandas:使用字典中元组的列标题和单元格值创建数据框
- java - Spring Cloud Gateway Filter Factory for Fire and Forget 模型
- php - 如果使用 andWhere(),Symfony 3.4 / createQueryBuilder 不起作用(ClassNotFoundException)
- r - RStudio 中与 Shiny 相关的问题
- flutter - 我对异步功能和屏幕上的更新信息有疑问
- javascript - 使用 localStorage 返回最后一次搜索