jquery ajax删除请求会删除一些但不是全部

问题描述 投票:0回答:1

这是一项学校作业。我用express创建了一个服务器,用jquery创建了一个app。它不是使用数据库,而是将jsons写入文件。

它就像Twitter,但它被称为Chirper,每个html段落就像一条推文,但被称为“唧唧”。我为每个chirp创建了一个删除按钮,用于向服务器发送ajax删除请求。按钮正在处理一些唧唧声,但不会对其他人发挥作用。通过工作,我的意思是,json chirp从json文件中删除。什么是阻止每个删除按钮工作的错误?

我先在这里复制了我的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
}
javascript jquery json express server
1个回答
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))
})

})

© www.soinside.com 2019 - 2024. All rights reserved.