简体   繁体   English

无法将变量传递到JavaScript中的Ajax网址中

[英]Can't pass variable into ajax url in javascript

I'm basically trying to delete an item in mongodb. 我基本上是想删除mongodb中的项目。 But I just can't seem to pass the id into the url in the ajax call. 但是我似乎无法将ID传递给ajax调用中的url。 Here's my code: 这是我的代码:

$(".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 
         });

I'm just learning at the moment, so I could be going about this the wrong way. 我现在只是在学习,所以我可能会以错误的方式进行操作。 If anyone can help me out, I'd appreciate it. 如果有人可以帮助我,我将不胜感激。

The error message is: 错误消息是:

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

As ajax calls are asynchronous, you should call itemDelete(id) from inside the first .done callback. 由于ajax调用是异步的,因此您应该从第一个.done回调内部调用itemDelete(id) Try moving 尝试移动

itemDelete(id);

just after 刚过

var id = newResult[0]._id;

This way you will execute your second ajax call only after the first has terminated, and the id variable will be defined. 这样,您将仅在第一个ajax调用终止后才执行第二个ajax调用,并且将定义id变量。

After the change your code should look like this: 更改后,您的代码应如下所示:

$(".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);
        });
    }
 });

This one should work for you. 这应该为您工作。

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

// Get ID first //首先获取ID

         $.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;
          itemDelete(id); // pass the id to the function 
        })
        .fail(function (jqXHR, error, errorThrown) {
            console.log(jqXHR);
            console.log(error);
            console.log(errorThrown);
        });



        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);
        });

        }


     });

Thanks 谢谢

The undefined in https://www.someplace.com/items/undefined suggests that the id is undefined. https://www.someplace.com/items/undefinedundefined表示ID未定义。 Note that the get and delete requests happen asynchronously, so id is not guaranteed to be set when you make the delete request, since it depends on when the request completes. 请注意,get和delete请求是异步发生的,因此不能保证在发出Delete请求时设置id ,因为它取决于请求完成的时间。 In other words, try deleting after you get the id. 换句话说,请获取ID 尝试删除。 This would require you to make the DELETE request in the success callback of the GET request. 这将要求您在GET请求的成功回调中发出DELETE请求。

Please try This one 请试试这个

 $.ajax({
            type: 'get',
            dataType : 'html',
            url: 'your_url',
            data:{variablname:id,type:'DELETE'}
            dataType: 'json',
        })

In your url page or action get the value as its type is get so the data type will be GET 在网址页面或操作中获取值,因为其类型为get,因此数据类型为GET

 if(isset($_GET['variablename'],$_GET['type'])){
     if($_GET['type']=='DELETE')
       delete record from database where id= $_GET['variablename']
}

I hope it will help you Thanks 希望对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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