我基本上是想删除mongodb中的项目。但是我似乎无法将ID传递给ajax调用中的url。这是我的代码:

$(".delete-item").on('click', function(e, id) {
              var deleteName = $('p.nameLink').text();

// Get ID first

             $.ajax({
                type: "GET",
                url: "/items",
                dataType: 'json',
            })
            .done(function(result) {

            // searches mongodb for the clicked name and saves the result in the var
             var newResult = $.grep(result, function(e){ return e.name === deleteName; });


              var id = newResult[0]._id;
            })
            .fail(function (jqXHR, error, errorThrown) {
                console.log(jqXHR);
                console.log(error);
                console.log(errorThrown);
            });

// Then delete

            console.log("ID to DELETE:", id);  // I can see id

            function itemDelete(id) {

             $.ajax({
                type: 'DELETE',
                url: '/items/' + id,
                dataType: 'json',
            })
            .done(function(result) {

           console.log("ID to DELETE:", id); // Can't see the id

            })
            .fail(function (jqXHR, error, errorThrown) {
                console.log(jqXHR);
                console.log(error);
                console.log(errorThrown);
            });

            }

            itemDelete(id); // pass the id to the function
         });




我现在只是在学习,所以我可能会以错误的方式进行操作。如果有人可以帮助我,我将不胜感激。

错误消息是:

删除https://www.someplace.com/items/undefined 500(内部服务器错误)

最佳答案

由于ajax调用是异步的,因此您应该从第一个.done回调内部调用itemDelete(id)。
尝试移动

itemDelete(id);


刚过

var id = newResult[0]._id;


这样,您将仅在第一个ajax调用终止后才执行第二个ajax调用,并且将定义id变量。

更改后,您的代码应如下所示:

$(".delete-item").on('click', function(e, id) {
    var deleteName = $('p.nameLink').text();

    $.ajax({
        type: "GET",
        url: "/items",
        dataType: 'json',
    })
    .done(function(result) {
        var newResult = $.grep(result, function(e){
            return e.name === deleteName;
        });

        var id = newResult[0]._id;
        itemDelete(id);
    })
    .fail(function (jqXHR, error, errorThrown) {
        console.log(jqXHR);
        console.log(error);
        console.log(errorThrown);
    });

    function itemDelete(id) {
        $.ajax({
            type: 'DELETE',
            url: '/items/' + id,
                dataType: 'json',
            })
            .done(function(result) {


            })
            .fail(function (jqXHR, error, errorThrown) {
                console.log(jqXHR);
                console.log(error);
                console.log(errorThrown);
        });
    }
 });

09-04 01:04
查看更多