简体   繁体   中英

Configuring a delete button with HTTP DELETE request (JavaScript)

I have a delete button that successfully deletes a list item in the DOM. But, it does not delete the item in the database, so when the page is refreshed the item reappears. This button is dynamically generated inside a HTTP GET request already as it is being retrieved from the database. Must I put it inside a another function within its parent XHTTP event listener?

xhttp.open("GET", items_url, true);
xhttp.addEventListener('load', function(){

    var item_list= document.querySelector('#divShowItems');
    item_list.innerHTML = "";

    var items = JSON.parse(this.response);

    items.forEach(function(item){

        var title = document.createTextNode(item.title);
        var id = document.createTextNode(item.id);
        var li_item = document.createElement('li');
        li_item.appendChild(title);
        li_item.appendChild(id);

        var deleteBtn = document.createElement("button");
        deleteBtn.innerHTML = "Delete";
        book_item.appendChild(deleteBtn);
        deleteBtn.addEventListener("click", function(e){ 
            this.parentNode.parentNode.removeChild(this.parentNode); 
        });
    })

If I got you correctly you are asking where to put code that would be sending HTTP DELETE request to the server when according button is clicked.

You need to have it inside delete button's click event listener, ie

deleteBtn.addEventListener("click", function(e){
    // build and send http delete here
    this.parentNode.parentNode.removeChild(this.parentNode); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM