【问题标题】:Ajax Search with select dropdown filters CakePhp使用选择下拉过滤器进行 Ajax 搜索 CakePhp
【发布时间】:2014-05-09 11:35:14
【问题描述】:

我想用下拉选择框构建一个 ajax searc 过滤器。 我会尽量说清楚。

我有一个类型学模型和控制器。类型学有

标识 |标题 |描述 | item_id |条件 ID |类别 ID |条件 ID |价格

其中 id 是主键,item_id、condition_id、category_id、condition_id 是外键。

因此,当类型索引页面加载时,它会显示所有类型的列表。

搜索表格如下:

<form name="search_form" id="search_form">  
                <li><p>tipologia</p>                     
                <?php    
                echo "<select name=\"typology_categories\" class=\"select_filter\" >";
                echo "<option value=''>All</option>";
                    foreach ($typologyCategories as $typologyCategory): 
                        $category_id = $typologyCategory['TypologyCategory']['id'];
                        $category_name = $typologyCategory['TypologyCategory']['name'];
                        echo "<option value='{$category_id}'>{$category_name}</option>";
                    endforeach;
                echo "</select>";                                   
                ?>
                </li>

                <li><p>localita</p>
                <?php 
                echo "<select name=\"item_locations\" class=\"select_filter\">";
                echo "<option value=''>All</option>";
                    foreach ($itemLocations as $itemLocation): 
                        $item_id = $itemLocation['ItemLocation']['id'];
                        $item_name = $itemLocation['ItemLocation']['name'];
                        echo "<option value='{$item_id}'>{$item_name}</option>";
                    endforeach;
                echo "</select>";
                ?>
                </li>
                <li><p>prezzo</p>
                    <select name="typology_price" class="select_filter">
                        <option value="">All</option>
                        <option value="1">0 - 1,000</option>
                        <option value="2">1,000 - 5,000</option>
                        <option value="3">5,000 - 50,000</option>
                        <option value="4">50,000 - 100,000</option>
                        <option value="5">100,000 - 500,000</option>
                        <option value="6">500,000 - 1,000,000</option>
                        <option value="7">more then 1,000,000</option>
                    </select>
                </li>
                <li><p>stato</p>
                <?php 
                echo "<select name=\"typology_conditions\" class=\"select_filter\">";
                echo "<option value=''>All</option>";
                    foreach($typologyConditions as $typologyCondition):
                        $condition_id = $typologyCondition['TypologyCondition']['id'];
                        $condition_name = $typologyCondition['TypologyCondition']['name'];
                        echo "<option value='{$condition_id}'>{$condition_name}</option>";
                    endforeach;
                echo "</select>";
                ?>
                </li>
                </form>

ajax 调用是:

    <!-- HERE IS THE SEARCH FILTER -->
    <script type="text/javascript" >
        $(document).ready(function () {
            $('.select_filter').bind("change keyup input",function() {
              $.ajax({
                   type: "POST",
                   url: "search.php", // This one should sent data to index action of the typology controller for processing
                   data: $("#search_form").serialize(), 
// You will get all the select data..
                    success:function(data){
                        $("#projects").html(data);
                    }
                });
          });
        });
    </script>

类型控制器是这样的: 索引操作:

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->set('title_for_layout', 'CESI');
        $this->layout='Homepage';

             // Typology Query
        $typologies = $this->Typology->find('all', array('recursive'=>-1, 'order' => array('Typology.' . $this->Typology->primaryKey . ' DESC')));
        $this->set('typologies', $typologies);

             // Typology Category Query
        $typologyCategories = $this->TypologyCategory->find('all', array('recursive'=>-1));
        $this->set('typologyCategories', $typologyCategories);
             // Typology Condition Query

        $typologyConditions = $this->TypologyCondition->find('all', array('recursive'=>-1));
        $this->set('typologyConditions', $typologyConditions);

            // Item Query       
        $items = $this->Item->find('all',array('recursive'=>-1));
        $this->set('items', $items);

            // Item Location Query
        $itemLocations = $this->ItemLocation->find('all', array('recursive'=>-1));
        $this->set('itemLocations', $itemLocations);

            // Slider Query
        $sliders = $this->Slider->find('all', array('recursive'=>-1));
        $this->set('sliders', $sliders);
    } 

所以我想用于我构建的搜索的查询是这样的:

<?php 
  /* Query for the Typology*/
          $queryTypologies = "SELECT * ";
          $queryTypologies .= "FROM typologies";
          $queryTypologies .= " WHERE  1=1 ";

        if (isset($_POST['typology_categories']) && !empty($_POST['typology_categories']) && $_POST['typology_categories']!='') {
           $queryTypologies .= " AND typology_category_id = (SELECT id FROM typology_categories WHERE id ='".trim(mysql_prep($_POST['typology_categories']))."' LIMIT 1)";
        }

        if (trim($_POST["item_locations"])!='' && !empty($_POST['item_locations'])) {
            $queryTypologies .= " AND item_id = (SELECT id FROM items WHERE item_location_id ='".trim(mysql_prep($_POST['item_locations']))."' LIMIT 1)";   //'".trim(mysql_prep($_POST['item_locations']))."'
        }
                            // value="1" 0         - 1,000
                            // value="2" 1,000     - 5,000
                            // value="3" 5,000     - 50,000
                            // value="4" 50,000    - 100,000
                            // value="5" 100,000   - 500,000
                            // value="6" 500,000   - 1,000,000
                            // value="7" more then - 1,000,000

        if (trim($_POST["typology_price"])!='' && !empty($_POST['typology_price']) && $_POST['typology_price']!='') {

            if (trim($_POST["typology_price"]) == 1) {  
                $queryTypologies .= " AND price <= 1000";                           
            }
            if (trim($_POST["typology_price"]) == 2) {  
                $queryTypologies .= " AND price BETWEEN 1001 AND 5000";                         
            }
            if (trim($_POST["typology_price"]) == 3) {  
                $queryTypologies .= " AND price BETWEEN 5001 AND 50000";                            
            }
            if (trim($_POST["typology_price"]) == 4) {  
                $queryTypologies .= " AND price BETWEEN 50001 AND 100000";                          
            }
            if (trim($_POST["typology_price"]) == 5) {  
                $queryTypologies .= " AND price BETWEEN 100001 AND 500000";                         
            }
            if (trim($_POST["typology_price"]) == 6) {  
                $queryTypologies .= " AND price BETWEEN 500001 AND 1000000";                            
            }
            if (trim($_POST["typology_price"]) == 7) {  
                $queryTypologies .= " AND price > 1000000";                         
            }
        }


        if (trim($_POST["typology_conditions"])!='' && !empty($_POST['typology_conditions']) && $_POST['typology_conditions']!='') {
            $queryTypologies .= " AND typology_condition_id = '".trim(mysql_prep($_POST['typology_conditions']))."' ";  
        }

          $typologies = mysql_query($queryTypologies) or die (mysql_error());

            $numrows = mysql_num_rows($typologies);
                        if($numrows != 0){
                                $result ="";
                                    while($rowTypologies= mysql_fetch_assoc($typologies)){

                                        $id                    = $rowTypologies['id'];
                                        $item_id               = $rowTypologies['item_id'];
                                        $title                 = htmlentities($rowTypologies['title'], ENT_COMPAT, "UTF-8");
                                        $description           = htmlentities($rowTypologies['description'], ENT_COMPAT, "UTF-8");
                                        $thumbnail             = htmlentities($rowTypologies['thumbnail'], ENT_COMPAT, "UTF-8");
                                        $price                 = htmlentities($rowTypologies['price'], ENT_COMPAT, "UTF-8");
                                        $typology_category_id  = htmlentities($rowTypologies['typology_category_id'], ENT_COMPAT, "UTF-8");
                                        $typology_condition_id = htmlentities($rowTypologies['typology_condition_id'], ENT_COMPAT, "UTF-8");

                                         if (strlen($description)>303) {
                                            $short_description = substr($description, 0, 300);
                                            $description = $short_description."...";
                                         }

                                        $first = base64_encode($item_id);
                                        $typologyThumbnails = "admin/app/webroot/img/uploads/typology/thumbnails/" . $thumbnail;
                                        $result .= "<div class=\"item_shadow\">";
                                        $result .= "<div class=\"item\" style=\"background-image:url({$typologyThumbnails});\">";
                                        $result .=  "<div class=\"item-content\">";
                                        $result .=      "<div class=\"item-top-content\">";
                                        $result .=          "<div class=\"item-top-content-inner\">";
                                        $result .=              "<div class=\"item-top-title\">";
                                        $result .=                      "<h4>{$title}</h4>";
                                        $result .=              "</div>";
                                        $result .=          "</div>"    ;
                                        $result .=      "</div>";
                                        $result .=      "<div class=\"item-add-content\">";
                                        $result .=          "<div class=\"item-add-content-inner\">";
                                        $result .=              "<div class=\"description-inner\">";
                                        $result .=                  "<p>{$description}</p>";
                                        $result .=              "</div>";
                                        $result .=              "<div class=\"read-more-inner\">";
                                        $result .=                  "<a href=\"new.php?id=$first\">maggiori informazioni <img src=\"img/elenco.png\"/></a>";
                                        $result .=              "</div>";
                                        $result .=          "</div>";
                                        $result .=      "</div>";
                                        $result .=  "</div>";
                                        $result .= "</div>";
                                        $result .= "</div>";

                                    }
                                echo $result;
                            } else {
                            echo "No Result Found in Database.";
                        }    
 ?>

我知道这是可行的,因为首先我在原始 php 编码上构建它,正如您自己看到的那样,它运行良好,但现在我想在 cakephp 上实现它。而且我还没有找到方法。

任何帮助将不胜感激!

提前感谢

【问题讨论】:

  • blog.jandorsman.com/blog/… 可能会有所帮助,它逐步解释了如何实现 ajax 填充的下拉菜单。它是为 Cake 1.3 编写的,但稍作修改后,它应该仍能以几乎相同的方式工作。
  • @Oldskool 我的意图不是填充下拉菜单,而是使用下拉菜单实现搜索

标签: jquery ajax cakephp cakephp-2.3


【解决方案1】:

当我搜索教程和 Cakephp Cook Book 时。我达到的最佳方法是:

首先:阻止 aJax 进行搜索的是安全组件。由于 cakephp 中的表单会生成一个唯一的令牌。每次提交都应该是不同的,所以因为我使用的是ajax,所以它会产生错误。所以我禁用了

public function beforeFilter() {    
     parent::beforeFilter();
        // Controller spesific beforeFilter
        $this->Auth->allow('search');
         if ($this->action == 'search') {
            $this->Security->validatePost = false;
            $this->Security->csrfCheck = false;

            if (!$this->RequestHandler->isAjax()) {
                $this->Security->blackHole($this, 'You are not authorized to process this request!');
                $this->redirect(null, 401, true);
            } 
        }
    }

然后我使用了 query(); cakephp 的方法,因为我的查询很复杂,并且它也使用了联接和条件。所以search()函数如下。

应用程序/控制器/控制器名称

/**
 * aJax search method
 *
 * @return void
 */
    public function search() {
    $this->autoRender = false;
        if ($this->request->is('post')) {
            if(!empty($this->data)){
                if ($this->request->is('ajax')) {

          /* Query for the Typology*/
          $queryTypologies  =" SELECT *";
          $queryTypologies .=" FROM typologies AS Typology";
          $queryTypologies .=" LEFT JOIN items as Item";
          $queryTypologies .=" ON Item.id = Typology.item_id";
          $queryTypologies .=" WHERE Item.published=1 AND Typology.published=1";          

        if (isset($this->data['Typology']['typology_categories']) && !empty($this->data['Typology']['typology_categories']) && $this->data['Typology']['typology_categories']!='') {
           $queryTypologies .= " AND Typology.typology_category_id ='".$this->request->data['Typology']['typology_categories']."'";
        }
        if (trim($this->data['Typology']['item_locations'])!='' && !empty($this->data['Typology']['item_locations']) && $this->request->data['Typology']['item_locations']!='') {
            $queryTypologies .= " AND Typology.item_id=(SELECT id FROM items AS Item WHERE Item.item_location_id='".$this->request->data['Typology']['item_locations']."' LIMIT 1)";
        }
        if (trim($this->request->data['Typology']['typology_price'])!='' && !empty($this->request->data['Typology']['typology_price']) && $this->request->data['Typology']['typology_price']!='') {

            if (trim($this->request->data['Typology']['typology_price']) == 1) {    
                $queryTypologies .= " AND Typology.price <= 1000";                          
            }
            if (trim($this->request->data['Typology']['typology_price']) == 2) {    
                $queryTypologies .= " AND Typology.price BETWEEN 1001 AND 5000";                            
            }
            if (trim($this->request->data['Typology']['typology_price']) == 3) {    
                $queryTypologies .= " AND Typology.price BETWEEN 5001 AND 50000";                           
            }
            if (trim($this->request->data['Typology']['typology_price']) == 4) {    
                $queryTypologies .= " AND Typology.price BETWEEN 50001 AND 100000";                         
            }
            if (trim($this->request->data['Typology']['typology_price']) == 5) {    
                $queryTypologies .= " AND Typology.price BETWEEN 100001 AND 500000";                            
            }
            if (trim($this->request->data['Typology']['typology_price']) == 6) {    
                $queryTypologies .= " AND Typology.price BETWEEN 500001 AND 1000000";                           
            }
            if (trim($this->request->data['Typology']['typology_price']) == 7) {    
                $queryTypologies .= " AND Typology.price > 1000000";                            
            }
        }
        if (trim($this->data['Typology']['typology_conditions'])!='' && !empty($this->data['Typology']['typology_conditions']) && $this->data['Typology']['typology_conditions']!='') {
            $queryTypologies .= " AND Typology.typology_condition_id='".$this->request->data['Typology']['typology_conditions']."'";    
        }
        $queryTypologies .=" ORDER BY Typology.id DESC";

                    $typologies = $this->Typology->query($queryTypologies);    
                    $this->set('typologies', $typologies);
                    /* debug($this->data); // This is used for development purposes ONLY!  */

                    if($this->RequestHandler->isAjax()){                        
                        $this->render('search', 'ajax');    
                    }               
                }
            }

        }
    }

在视图中我使用了这个 Ajax:

<!-- HERE IS THE SEARCH FILTER -->
 <script type="text/javascript" >
 //<![CDATA[
    $(document).ready(function () {
        $('.select_filter').bind('change keyup input',function(event) {
            $('html,body').animate({ scrollTop: $("#work").offset().top}, "slow");
            var formData = $('#search_form').serialize(); 
            $.ajax({
                async:true, 
                data: formData, // You will get all the select data..
                dataType:'html',
                success:function(data){
                    $("#projects").html(data);
                },
                type: 'POST',
                url:'<?php echo Router::Url(array('controller' => 'typologies','admin' => false, 'action' => 'search'), true); ?>'
            });
            event.preventDefault();
            return false;
        });
    });
//]]>
 </script>

这对我来说是一种魅力。随意使用它。我希望它对任何人都有用。

【讨论】:

    【解决方案2】:

    我想你可以正常进行查找,就像你在index() 页面上所做的那样。 似乎您无法将 ajax 响应返回给客户端。

    为此,您可以使用json views,这样您就可以在控制器上进行搜索(在search() 方法中)并在视图中渲染,并将其作为ajax 响应返回,而不是全部放在同一个将它放在您的原生 PHP 代码中。

    请查看此链接了解如何使用它:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#using-a-data-view-with-view-files

    【讨论】:

      【解决方案3】:
      public function beforeFilter() {    
       parent::beforeFilter();
          // Controller spesific beforeFilter
          $this->Auth->allow('search');
           if ($this->action == 'search') {
              $this->Security->validatePost = false;
              $this->Security->csrfCheck = false;
      
              if (!$this->RequestHandler->isAjax()) {
                  $this->Security->blackHole($this, 'You are not authorized to process this request!');
                  $this->redirect(null, 401, true);
              } 
          }
      }
      

      函数对于使用 CakePHP 2 的代码初学者很有帮助,它有一个带有背景运行时的父函数。

      【讨论】:

        猜你喜欢
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        相关资源
        最近更新 更多