妄徒之命 2016-03-24 14:08 采纳率: 100%
浏览 94

Ajax和Mongodb,使用_id

I have a test project using express.js that displays all items in a mongo database on a webpage. Each database entry is displayed on the page with a button to delete it.

-each i in docs
        p ----------------------
        p <strong>Name: #{i.name}
        p <strong>Type: #{i.type}
        p <strong>Amount: #{i.quantity}
        p <strong>ID: #{i._id}    
        input(type = 'button', value ="delete item", id='delete')

I want the button to send a DELETE request to /api/item/_id

My script is as follows

script(type='text/javascript').
        $(document).ready(function() {
            $("#delete").click(function() {

                $.ajax({
                    type: 'DELETE',
                    url: '/api/item/' + this._id
                }).done(function(result) {

                });
            });
        });

This is not sending the desired request. How would I go about passing the _id from the item to the button?

If I set the URL to a know _id, like below, it works and the item is deleted

url: '/api/item/56f3e800d6f24d0819e43fcc'

Thanks in advace

  • 写回答

2条回答 默认 最新

  • weixin_33691598 2016-03-24 14:17
    关注

    Use data- attribute

    Html

    <input type="button" id="delete" data-id="mongo id here" />
    

    JS

     $.ajax({
       type: 'DELETE',
       url: '/api/item/' + this.attr('data-id')
     })
    

    Also you'd better use class instead of id="delete"

    评论

报告相同问题?