В этой статье приведен пример PHP + Ajax для достижения функции сравнения товаров. Чтобы поделиться с вами для вашей справки, следующим образом:
JS-файл вызова для сравнения товаров (включая плавающий JS-файл для сравнения товаров):
/*Floating window*/ (function(){ var n=10; var obj=document.getElementById("goods-compare"); if(!obj){ return false; } var x=0; window.onscroll=function(){ obj.style.top=(document.body.scrollTop||document.documentElement.scrollTop)+n+'px'; }; window.onresize=function(){ obj.style.top=(document.body.scrollTop||document.documentElement.scrollTop)+n+'px'; }; })(); //Add display contrast box function addcompare(chk){ $('#goods-compare').fadeIn().show(); var count=$(".compare-box li").length; If (count > 2) // you can modify the comparison data here { Alert ('select 3 products at most for product comparison '); return; } $.ajax({ type: 'post', url: 'ajax.php', data: { 'action':'1', 'GID': chk.gid, // commodity ID 'gname': chk.gname, // commodity name 'gType': chk. GType // product categories cannot be compared when they are different }, cache: false, async: false, success: function(result) { if(result!='') { alert(result); }else{ Var url ='http://www.lusen.com/product - '+ chk. GID +'. HTML '; // set the link address of the product $(". Compare box"). Append ("< Li class ='Division Clearfix 'id ='" + chk. GID + "') < div class ='span-3' > a href = '" + URL + "' target = '[blank' title = '" + chk. Gname + "'" '+ chk. Gname + "' < / a > < div > < span onclick =" removecompare ('"+ chk. GID +"'); \ "> delete < / span > < li >") $("comids"). Val ($(". Compare box Li"). Map (function() {// assign all commodity IDs of comparison to "comids" return $(this).attr('id'); }).get().join(",")); } } }); } //Delete comparison products function removecompare(id) { $.ajax({ type: 'post', url: 'ajax.php', data: { 'action':'2', 'gid':id }, cache: false, success: function(result) { $("#"+id).remove(); $("#comids").val($(".compare-box li").map(function(){ return $(this).attr('id'); }).get().join(",")); } }); } //Empty comparison products function clearcompare() { $.ajax({ type: 'post', url: 'ajax.php', data: { 'action':'3' }, cache: false, success: function(result) { $(".compare-box").html(''); $("#comids").val(''); } }); } //Show contrast box function showcompare() { $.ajax({ type: 'post', url: 'ajax.php', data: { 'action':'4' }, success: function(result) { if(result){ $(".compare-box").append(result); $("#comids").val($(".compare-box li").map(function(){ return $(this).attr('id'); }).get().join(",")); $('#goods-compare').fadeIn().show(); } } }); } //Click to close the comparison box $('.close-gc').click(function(){ $('#goods-compare').fadeOut().hide(); });
Сравнение продуктов вызывает файл Ajax:
2) {// product comparison quantity Echo "select at most 3 kinds of goods for comparison"; return; } foreach($arr as $val) { if($val[0]==$_POST['gid']) { Echo "the product has been added to the comparison box"; return; } } $info=array($_POST['gid'],$_POST['gname'],$_POST['gtype']); $arr[]=$info; $arr_str=serialize($arr); setcookie('gid',$arr_str); }else { $info=array($_POST['gid'],$_POST['gname'],$_POST['gtype']); $arr[]=$info; $arr_str=serialize($arr); setcookie('gid',$arr_str); } }else if($_POST['action']=='2') {//delone $id=$_POST['gid']; $arr_str = $_COOKIE['gid']; $arr=mb_unserialize($arr_str); foreach($arr as $key=>$val) { if($val[0]==$id) { unset ($arr[$key]); } } $arr_str=serialize($arr); setcookie('gid',$arr_str); }else if($_POST['action']=='3') {//delall setcookie('gid',''); setcookie('gtype',''); }else if($_POST['action']=='4') {//showlist if(isset($_COOKIE['gid'])) { $data=''; $arr_str = $_COOKIE['gid']; $arr=mb_unserialize($arr_str); foreach ($arr as $val){ $url="http://www.lusen.com/product-".$val[0].".html"; $data. = "< Li id = '{$Val [0]}' class ='Division Clearfix ': < div class ='span-3' > a href = '{$URL}' target = '[blank' title = '{$Val [1]}' {$Val [1]}) < / a > < div > < span onclick = \" removecompare ('{$Val [0]}'); \ "> delete < / span > < / Li >"; } echo $data; } } ?>
Для получения дополнительной информации о PHP читатели, интересующиеся PHP, могут обратиться к следующим темам: Резюме навыков и приложений PHP + Ajax, резюме навыков сетевого программирования PHP, учебник по основному синтаксису PHP, учебник по объектно-ориентированному программированию PHP, краткое описание использования строк PHP, руководство по работе с базой данных PHP + MySQL и общее резюме навыков работы с базой данных PHP “
Я надеюсь, что эта статья будет полезна для программирования на PHP.