我使用 nodejs、nowjs、codeigniter 和 mysql 编写应用程序。我使用数据库来存储会话。有没有一种好方法可以在nodejs中检查和检索会话cookie?因此,例如,如果这样,我需要使用 nowjs 检查用户是否拥有数据库中即将被删除的特定行。例如:
服务器:
//some code here to get session cookie and retrieve stored data from database
var session = { user_id: //userid from database }
everyone.now.deleteGuestbook = function(recordId) {
var owner_id = client.query(
'SELECT owner_id FROM guestbook WHERE id = ?',
[recordId]
);
if (session.user_id === owner_id) {
client.query(
'DELETE FROM guestbook WHERE id = ?',
[recordId], function() {
everyone.now.deleteRecord;
}
);
}
}
客户:
//Delete guestbook record
$('#guestbook_records li').live('click', function(e) {
if ($(e.target).is('a.delete')) {
var id = $(this).find('a.delete').attr('href');
dialogBox('warning', 'Are you sure you want to delete the record?',
function() {
now.deleteGuestbook(id);
});
}
else {
return;
}
return false;
});
now.deleteMessage = function(id) {
$('li[class="' + id + '"]').slideUp(400, function() {
$(this).remove();
});
};
会话 ID 通常保留在客户端 cookie 中,这些 cookie 在 httpServer 处理程序中显示为 request.headers.cookie。
您需要知道包含会话 ID 的 Cookie 的名称,然后:
var cookies=(function(str){ # create hash from cookie string
var result={};
str.split(/;'s+/).forEach(function(e){
var parts=e.split(/=/,2);
result[parts[0]]=parts[1]||'';
});
return result;
})(request.headers.cookie),
sessionCookieName='session', # name of cookie holding session id
sessionId=cookies[sessionCookieName]||''; # session id or ''
你的客户端代码很乱
// live is bad and inefficient
$('#guestbook_records li').live('click', function(e) {
// this kind of check seems horrid
if ($(e.target).is('a.delete')) {
// not very optimum to find it.
var id = $(this).find('a.delete').attr('href');
dialogBox('warning', 'Are you sure you want to delete the record?',
function() {
now.deleteGuestbook(id);
});
}
else {
// why return here?
return;
}
// return false should be in if block.
return false;
});
试试这个
$("#guestbook_records li a.delete").click(function(e) {
var id = this.href;
dialogBox("warning", "Are you sure you want to delete the record?",
function() {
now.deleteGuesBook(id);
});
e.preventDefault();
}
也.hasClass
更好
now.deleteMessage = function(id) {
$('li').hasClass(id).slideUp(400, function() {
$(this).remove();
});
};