我使用PHP在页面上列出了一个项目列表。我想添加一个简单的Ajax切换功能,允许用户在浏览时将列表中的项目设置为书签。
如果Item->bookmark field=1,则项目被标记为书签,并且应该显示一个简单的图像。当他们再次单击它时,它会使MySQL中的it=“0”,书签图像将更改回其他内容。
在不重新加载页面的情况下,最好的方法是什么?
I feel like you could have googled "jquery ajax example" but here you go...
HTML:
<div class="container">
<div class="item" id="<?php echo $whateverYourIdIs; ?>">Bookmark me!</div>
</div>
jQuery:
$(document).ready(function(){
$('.item', $('.container')).click(function(){
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "some.php",
data: { id: id }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
AJAX is the way to go to save data on the server. But if you want to add / remove bookmark on the fly while on the page, you can use a function that toggle bookmark on and off, using data-* attributes
$(".bookmarkButton").click(function(){
if(! $(this).parent().data('bookmark')){
alert('bookmarked');
$(this).parent().data('bookmark', 1);
// Add image + AJAX call
}
else {
alert('not bookmarked');
$(this).parent().data('bookmark', null);
// Remove image + AJAX call
}
});
Here's a simple JSFiddle : http://jsfiddle.net/YwTuB/