当登录的用户单击“收藏夹”按钮时,我无法将信息保存到。
这是我上JavaScript课(包括Ajax)的第一周。只要我们了解此过程,就可以复制粘贴。因此,我要做的第一件事是查找有关如何制作“收藏夹” /“收藏夹”按钮的教程,并接管了模板。然后,我搜索了用户单击“收藏夹”按钮后如何将信息保存在数据库中。我不确定是否允许链接到外部网站,但我专门接管了此代码:
document.body.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
var text = target.textContent;
console.log(text);
var id = target.getAttribute('id');
console.log(id);
var name = target.getAttribute('name');
console.log(name);
var Class = target.getAttribute('class');
console.log(Class);
}, false);
它会像预期的那样显示“将我添加到收藏夹”,但是当我单击它时,它返回:
<!DOCTYPE html>
<html>
<head>
<title>New page name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
/*
* Erase cookie with name.
* You can also erase/delete the cookie with name.
*/
function eraseCookie(name) {
createCookie(name, '', -1);
}
var faves = new Array();
$(function(){
var url = window.location.href; // current page url
$(document.body).on('click','#addTofav',function(e){
e.preventDefault();
var pageTitle = $(document).find("title").text();
var fav = {'title':pageTitle,'url':url};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
$(document.body).on('click','.remove',function(){
var id = $(this).data('id');
faves.splice(id,1);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
faves = myfaves;
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.title+'</h4> <a href="'+value.url+'">Open page</a> '+
'<a href="javascript:void(0);" class="remove" data-id="'+index+'">Remove me</a>';
$('#appendfavs').append(element);
});
});
</script>
</head>
<body>
<a href="javascript:void(0);" id="addTofav">Add me to fav</a>
<ul id="appendfavs">
</ul>
</body>
</html>
分配如下:
“”-显示“收藏夹”图标/心。通过jQuery / JavaScript使其可单击。如果单击它,则必须发送带有博客文章ID的AJAX请求。 WP插件必须“处理” AJAX请求,并存储用户X喜欢某个博客文章的会话(或数据库)。服务器必须返回JSON响应。”
现在有一个小问题,因为在我解决了该线程的错误之后,我的想法是正确的:
谢谢你提前堆栈溢出,我期待着学习!