我目前正在为加入我网站的新用户制作"欢迎/演练"。
最初,他们将受到他们可以喜欢的最近/热门上传的欢迎,这将有助于我的网站找到他们想要的图像。但我的问题是让用户选择他们喜欢或不喜欢的最佳方式是什么?目前我有这个。
http://jsfiddle.net/BKjJV/
我希望你能掌握我在这里想要实现的目标,但如果没有,总结一下,
用户点击 (n) 喜欢的图像数量 ->点击继续 ->页面抓取所有喜欢的图像并将它们发送到添加到我的数据库中的文件。
给定
代码的最简单方法是"下一页按钮"查看用户选择了哪些图像,并通过AJAX将它们的名称发送到PHP页面,该页面将在数据库中检查以添加它们:
$(document).ready(function(){
var images = new Array(); //images clicked will be stored here
$('#next_page_button').click(function(e){ //button that will send users to the next page
e.preventDefault();
$('.item').each(function(){ //for each image
if($(this).find('.clicked').is(":visible")){ //see if the user has clicked on it
images.push($(this).find('img').attr('src')); //and if so add it to the array
}
});
$.ajax({ //time to send it to the php page
url: '', //url of it
type: 'POST',
data: {images: encodeURIComponent(images.join())}, //lets merge the array and create a query string of the image separated by a comma and encode them to be sent via POST
success: function(data){
//if the database actions went well, user will be send to the next page
}
});
});
});
在PHP页面上,您将检索$_POST['images']
,通过explode(',' $_POST['images'])拆分变量,然后通过数组进行检查/添加到数据库中foreach
小建议:您应该使用 id 来创建"唯一"图像并将其显示在页面上,以便更轻松地在数据库中"检查/添加"它们。使用唯一的数字索引而不是文本比较速度更快,并且可靠性更高。
你可以用简单的方式做,javascript 代码是
$('#continue').on('click', 'input', function(e) {
var selection = [];
$('.item').filter(function() {
return $(this).find('.clicked').css('display') == 'block';
}).each(function() {
selection.push($(this).find('img').attr('src'));
});
alert(JSON.stringify(selection));
$.post('http://www.example.com', {
"selection": JSON.stringify(selection)
}, function(data) {
console.log(data);
});
return false;
});
查看更新的小提琴演示