CakePHP中的AJAX JSON和路由 [英] AJAX JSON and routing in cakephp

查看:111
本文介绍了CakePHP中的AJAX JSON和路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AJAX来实现搜索模块.

I am trying to implement a search module by using AJAX.

我的项目控制器中有一个index.ctp文件,并且我已将我的项目的index.ctp文件链接到我的search.ctp文件中,该文件位于页面控制器下,如下所示:

There is an index.ctp file in my Items Controller and I have linked my index.ctp file of Items to my search.ctp file which is present under Pages controller as below:

<li><?= $this->Html->link(__('Search Products'),['controller'=>'Pages','action' => 'search']) ?></li>

对于search.ctp页面,显示的URL为: http://onlineelectronic.com/pages/search

For the search.ctp pages the URL displayed is : http://onlineelectronic.com/pages/search

在我的search.ctp文件中,代码如下:

In my search.ctp file the code is as follows:

    <head>
    <title> Search Results</title>
    <?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => false));?>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#Submit1").click(function () {
                $.ajax({
                    type: 'post',
                    url: '/Items/searchData",
                    data: {
                        name: "search"
                    },
                    beforeSend: function(){
                        $("#resultField").html("Loading...");
                    },
                    success: function(response) {
                        jQuery('#resultField').val(response);
                    },
                    error: function(response, error) {
                        alert("Search :Error"+response.error());
                    },
                    dataType: 'json',
                    global: false
                });
               return false;
            });
        });
    </script>
</head>

<div>
    <?= $this->Form->create() ?>
    <fieldset>
        <legend><?= __('Search Item') ?></legend>
        <?php
        echo $this->Form->input('search',['label'=>'Search']);
        ?>
    </fieldset>

    <?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
    <?= $this->Form->end() ?>

</div>

<div id="resultField">

</div>

在我的ItemsContoller页面中,searchData方法是这样实现的:

In my ItemsContoller page the searchData method is implemented like this:

    class ItemsController extends AppController
{


    public $helpers = ['Form', 'Html', 'Time'];

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }

    public function search(){
    //dummy
    }

    /**
     *obtains search result for a given string.
     */
    public function searchData()
    {
        $this->layout = 'ajax';
        echo "here";
        $search_data=[];
        var_dump($search_data);
        //$search_results = [];
        if ($this->request->is('post')) {
            $search_data= $this->request->data;
            $search_data=implode("|",$search_data);
            $search_results = $this->Items->find('all', array('conditions'=>array('Items.itemName LIKE'=>"%$search_data%")));
            if(!empty($search_results)) {
                $this->set(compact($search_results));
                $this->set('_serialize',array('search_results'));
                return json_encode($search_results);
            }
        }

    }



    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);

        $this->Auth->allow(['index', 'view','search','searchData']);


    }
}

我的问题是SearchData方法没有被调用,我也没有收到任何JavaScript错误.如何确保按下按钮后按下该方法,这是由于json中的url吗?

My issue is that the SearchData method is not being called and I am not getting any javascript errors also.How do i make sure that the method gets called on pressed after pressing the button.Is it due to the url in json?

推荐答案

我看到2种可能的问题.首先,在ItemsController中,必须允许searchData方法

I see 2 possible problems. First in ItemsController, you have to allow searchData method

// change this line
$this->Auth->allow(['index', 'view','search']);
// to this
$this->Auth->allow(['index', 'view','searchData']);

还请确保您具有正确的jQuery选择器

also make sure, that you have proper jQuery selector

// try to change this line
<?= $this->Form->button('Search Items',['label'=>'Submit1']); ?>
// to this
<?= $this->Form->button('Search Items',['id'=>'Submit1']); ?>

编辑:对javascript进行了更正:

make more corrections to javascript:

  1. 使用ajax传递的数据应加双引号

  1. Data passed with ajax should be double quoted

data: {
    name: "search"
},

  • 在点击处理程序的末尾添加return false;,以防止提交表单和重新加载页面

  • add return false; to the end of click handler, so you prevent submiting form and reloading page

    还请注意,您必须在Template/Items/search_data.ctp

    这篇关于CakePHP中的AJAX JSON和路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆