使用模块 class 中的 ajax 处理 <select> 值,prestashop 1.6

Handle <select> values with ajax in module class, prestashop 1.6

我正在开发一个 ps 模块,可以让您 class 确定类别中的产品附件并将它们显示在首页产品页面中。

我正在使用带有附件的可拖动列表,当您将它们拖放到类别时,它会变成一个选项标签,每个类别都有一个 select 标签,用于放置附件。

我想保存附件和它们被丢弃的类别,所以我想调用 ajax 将数据带到我的模块 class 但我是新手 ajax 无法接近它。

这是我做的:

js 代码(在正确的 .tpl 内):

<script>
        $( ".droptrue" ).droppable({
                
                drop: function( event, ui ) {
                    //add <option> tag when an attachment is dropped to category's select
                    $(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
                    //remove the <li> wich contained the attachment data
                    ui.draggable.fadeOut("slow").remove();
                    
                    var val = $('#categoryAttachmentArr').val();
                  //var tab = val.split(',');
                  //for (var i=0; i < tab.length; i++)
                  //if (tab[i] == $(this).val())
                  //     return false;
                    //create an array with the next format: 'id_category(1)'-'id_attachment(1)','id_category(2)'-'id_attachment(2)'[....]
                    //the comma will be the main character that will be splitted
                    $('#categoryAttachmentArr').val(val + ui.doppable.attr('id') + '-' + ui.draggable.attr('id') +',');
                }
        });
        
        $('#submitAddProduct').click(function(e){
            $.ajax({
              type: 'POST',
              url: baseDir + 'modules/adjuntos/classes/CategoryAttachment.php',
              data: {
                        ajax: true,
                        action: \'CategoryArray\',
                        cat_array: $('#categoryAttachmentArray').val(),
                    }
              dataType: 'json',
              success: function(json) {
                console.log($('#categoryAttachmentArray').val());
              }
        });
        })
    
        $( ".ui-state-default" ).draggable({ 
                
                revert: "valid",
            
        });
</script>

还有我的 class:

class CategoryAttachment extends Objectmodel
{
     //other functions
     public function ajaxProcessCategoryArray()
    {
        $CategoryAttachmentArr = Tools::getValue('cat_array')
    }
}

您无法直接连接到任何 class。您必须使用控制器来执行此操作。

Ajax 发送数据到控制器

控制器使用 class

保存数据

控制器 return 结果到浏览器 (javascript)

终于找到解决办法了,说不定你们中的某个人以后也会遇到这个问题呢。

我在 .tpl 中的代码:

$( ".ui-state-default" ).draggable();

        $( ".droptrue" ).droppable({

                drop: function( event, ui ) {
                    //add <option> tag when an attachment is dropped to category's select
                    $(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
                    $('#selectAttachment1').append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>')
                    //remove the <li> wich contained the attachment data
                    ui.draggable.fadeOut("slow").remove();

                    var val = $('#categoryAttachmentArr').val();
                    //make a serialize() type array
                    $('#categoryAttachmentArr').val(val + $(this).attr('id') + "=" + ui.draggable.attr('id') +"&");

                    var value = $('#arrayAttachments').val();
                    var tab = value.split(',');
                    for (var i=0; i < tab.length; i++)
                        if (tab[i] == ui.draggable.attr('id')){

                            return false;
                        }
                    $('#arrayAttachments').val(value+ui.draggable.attr('id')+',');

                }
        });


        $('#submitCategories').click(function(e){
            var array = $('#categoryAttachmentArr').val()
            $.ajax({
              url: '../modules/adjuntos/ajax-call.php',
              data: {
                  action: 'handlearray',
                  token:new Date().getTime(),
                  cat: array
              },
              method: 'POST',
              success:function(data){
               $('#result').html(data);
             }
        });
        });

ajax 调用转到我的 ajax-call.php 文件:

<?php
 //load ps config
 require_once(dirname(__FILE__).'../../../config/config.inc.php');
 require_once(dirname(__FILE__).'../../../init.php');
 require_once('adjuntos.php');
 //adjuntos.php is the name of my module main file
 if(Tools::getIsset('token') && Tools::getIsset('action'))
 {
     $mp = new Adjuntos;
     echo $mp->handleArray();
 }

我的模块主文件中的 handleArray 函数:(它调用我的自定义 class)

public static function handleArray()
{

    $html = '';
    $array = Tools::getValue('cat');
    $arrayExplode = explode("&", $array);
    foreach($arrayExplode as $value)
    {
        $finalArr = explode("=", $value);
        if (!CategoryAttachment::postProcess($finalArr))
        {
            $html .= '<p style="color:red;>Fallo</p>"';
        }     
    }
    $html .= '<p style="color:green;>Correcto</p>"';
    return $html;
  }

我自定义的函数class:

public static function postProcess($finalArr)
    {

        return Db::getInstance()->execute(
                'UPDATE ps_attachment SET id_category = '.$finalArr[0].' WHERE id_attachment = '.$finalArr[1]
               );


    }//end 

这种方式非常有效,并使代码更具可扩展性