【问题标题】:jquery ajax delete request deletes some but not alljquery ajax删除请求删除一些但不是全部
【发布时间】:2019-02-05 19:16:21
【问题描述】:

这是一个学校作业。我用 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
}

【问题讨论】:

  • 此外,您的删除逻辑中存在逻辑错误,因为您正在使用元素的索引来确定要删除哪个元素。考虑以下。你有 5 个啁啾声。你删除了第四个啁啾。现在你的 json 文件有 4 个啁啾声。现在您尝试删除索引为 5 的啁啾。但文件中只有 4 个啁啾。您不能可靠地使用基于索引的映射将前面的啁啾声与文件中的啁啾声相关联。无论索引是否更改,您都需要某种其他形式的标识符来匹配。编辑:这是假设您使用的是数组。
  • @Taplar,我正在研究你的答案。对于第一个,这看起来对吗:$(document).on("click", ".delete", event =&gt; { // set variable for the button's parent (the chirp) let chirpToDelete = $(event.target).parent()
  • 是的,它应该接受作为事件处理程序的箭头函数中的事件。
  • 在我的脑海中,我可能会说,给每个啁啾一个创建时间戳,以毫秒为单位。您可以使用它作为您传递的标识符以知道要删除哪个。
  • 嗯,也许我解释得不够好。 let time = (new Date().getTime()) 当您在页面上显示啁啾时,您正在为它生成一个时间戳。在页面上显示啁啾不是在创建啁啾时。啁啾是在插入 JSON 文件时创建的。 JSON 文件需要在每个啁啾上都有创建时间戳。当您从服务器检索啁啾时,该请求需要返回每个啁啾的时间戳,客户端只需将返回的时间戳附加到相关的啁啾。所以 JSON 中的时间戳匹配页面上的啁啾声

标签: javascript jquery json express server


【解决方案1】:
$(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))
})

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多