我想实现一个简单的AJAX GET请求。这个请求告诉服务器在数据库中删除文件。虽然我得到证实,从该文件被删除了服务器,Chrome的检查表明,请求坐作为待定,最终导致了服务器错误。
我在做什么错误?
HTML
< DIV CLASS =删除音符>
< A HREF =#><我类=图标,减号>< / I>< / A>
< / DIV>
JS
$('删除音符)。点击(函数(五){
VAR URL ='/文档/+ DOC_ID +'/ note_destroy /+ note_id;
$阿贾克斯({
键入:GET,
网址:网址,
缓存:假的,
});
即preventDefault();
});
编辑:包括服务器端code,以及:
节点/ EX preSS
exports.note_destroy =功能(REQ,RES){
Doc.findOne({DOC_ID:req.params.doc_id},功能(ERR,数据){
如果(ERR)掷(ERR);
note_id = req.params.note_id;
data.notes.id(note_id)上卸下摆臂();
data.save(功能(错误){
如果(ERR)掷(ERR);
的console.log('注意'+ note_id +被删除。');
});
});
};
解决方案
您的服务器端功能不写任何回应,所以浏览器会无限期地等待。试着写一个回应,也许某种状态code。该客户端可以查看告诉删除是否有效。喜欢的东西...
res.writeHead(200,{内容类型:应用/ JSON'});
res.write(JSON.stringify({状态:OK}));
res.end();
I am trying to implement a simple AJAX GET request. This request tells the server to delete a document in a database. While I get confirmation from the server that the document is deleted, the Chrome Inspector shows that the request sits as "pending", eventually resulting in a server error.
What am I doing incorrectly?
HTML
<div class="delete-note">
<a href="#"><i class="icon-minus-sign"></i></a>
</div>
JS
$('.delete-note').click(function(e) {
var url = '/docs/' + doc_id + '/note_destroy/' + note_id;
$.ajax({
type: "GET",
url: url,
cache: false,
});
e.preventDefault();
});
Edit: Including server-side code as well:
Node/Express
exports.note_destroy = function(req, res) {
Doc.findOne({ doc_id : req.params.doc_id }, function(err, data) {
if (err) throw (err);
note_id = req.params.note_id;
data.notes.id(note_id).remove();
data.save(function(err) {
if (err) throw (err);
console.log('note ' + note_id + 'is removed.');
});
});
};
解决方案
Your server-side function doesn't write any response, so the browser waits for it indefinitely. Try writing a response, perhaps with some kind of status code that the client-side can check to tell whether the deletion worked. Something like...
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ status: OK }));
res.end();