我有一個網頁顯示了「資源」(又名MongoDB集合中的一個條目),並且在該網頁上我想要一個「刪除」按鈕,它將發送一個「刪除」請求到服務器正確的路線。 路由器的工作原理(所以當我使用外部程序發送刪除請求時,該條目被刪除),但我想要一個鏈接。如何使用button和jquery向節點發送DELETE請求?
顯然,在做了一些研究後,我需要使用ajax函數來做到這一點,如this post。問題是我不能使它工作(可能是因爲我剛開始使用jQuery),當我點擊按鈕時似乎沒有任何反應。但是,如果我嘗試一個簡單的警報(),它的工作原理是('#delete').on('click',function(){ alert('clicked')});
。
所以
下面是基本的html:
$('#delete').on('click', function() {
alert('click');
//here would be the code to send the DELETE request ?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Storystrap Template</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- bower:css -->
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css" />
<!--endbower-->
<!-- bower:js -->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/printplugin.min.js"></script>
<!--inject:js-->
<script src="/js/app.js"></script>
<script src="/js/modernizr-custom-touch.js"></script>
</head>
<body>
<button class="delete" data-target="/" data-method="DELETE" data-disabled="true">Delete Ressource</button>
</body>
</html>
這裏是在node.js的路由代碼(此代碼的工作,如果我手動發送DELETE請求),該id應該在頁面的鏈接中
ressourcesRouter.route('/ressources/t/:ressourcesId')
// permet d'afficher UNE ressource spécifique
.get(function(req,res){
var returnRessource = req.ressource.toJSON();
res.render('ressourceView', {
title: 'Ressources',
ressource: returnRessource
});
})
.delete(function(req,res){
req.ressource.remove(function(err){
if(err)
res.status(500).send(err);
else{
res.status(204).send('Removed');
console.log('ressource supprimée');
}
});
});
你能幫我找出需要的ajax代碼嗎?還是有另一種方式? 如有需要,請隨時索取更多代碼,我會盡可能迅速地回覆您。
此致敬禮。
所以使Ajax調用。你試過的確切代碼是什麼都行不通? – epascarello
'#'代表id,但您的刪除按鈕有類。所以使用'.delete'而不是'#delete' –
@epascarello鏈接上的一個,但它似乎有什麼問題,我的jQuery。 – Xogno