NodeJs通过jQuery / ajax

时间:2018-04-16 12:45:18

标签: jquery node.js ajax

我在服务器端有这个代码

 router.delete('/categories/delete/:id', function(req,res){
         var id = req.params.id;
          Category.remove({_id: id},function(err){
               if(err){
                    console.log(err);
               }
               req.flash('success','Category Deleted');
               res.location('/manage/categories');
               res.redirect('/manage/categories');
          });
    });

在dustjs视图中,我有这个按钮<a href="#" class="removeCategory button tiny alert" data-id="{._id}">Delete</a>

在脚本文件中我有

$(document).ready(function(){
    $('.removeCategory').on('click', function(e){
        $target =  $(e.target);
        var id = $target.attr('data-id');
        $.ajax({
            type: 'DELETE',
            url: '/manage/categories/delete/'+id,
            success: function(response){
                alert('Delete');
                window.location = '/manage/categories';
            },
            error: function(err){
                console.log(err);
            }

        });
    });

});

事情是它有点工作,但只有在刷新页面后类别才会消失,但是当我看到控制台时,我会收到这样的消息:

abort: function abort()
​
always: function always()
​
complete: function add()
​
done: function add()
​
error: function add()
​
fail: function add()
​
getAllResponseHeaders: function getAllResponseHeaders()
​
getResponseHeader: function getResponseHeader()
​
overrideMimeType: function overrideMimeType()
​
pipe: function then()
​
progress: function add()
​
promise: function promise()
​
readyState: 4
​
responseText: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /manage/categories</pre>\n</body>\n</html>\n"
​
setRequestHeader: function setRequestHeader()
​
state: function state()
​
status: 404
​
statusCode: function statusCode()
​
statusText: "Not Found"
​
success: function add()
​
then: function then()

我还想提一下警告框永远不会出现。有谁知道如何解决这个问题?提前谢谢

1 个答案:

答案 0 :(得分:1)

看起来你调用的url不正确,responseText属性给出了一个提示:

Cannot DELETE /manage/categories

这就是你调用错误处理程序的原因:

error: function(err){
  console.log(err);
}

而不是成功。

您确定ID是否正确?