CakePHP试图发送一个ajax请求

时间:2013-11-11 16:52:45

标签: php jquery cakephp

我正在尝试向控制器发送一个ajax请求,它应该返回一些东西,但不是。 我的元素(View / Elements / list.ctp):

<script type="text/javascript">
    $(document).ready(function(){
        $('#click').click(function(){
            $.ajax({
                type: "POST",
                url: '<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>',
                success: function(data){
                    alert(data);
                }
            });
        });
    });
</script>
<p id="click">Click me!</p>

控制器产品:

<?php
    class ProductsController extends AppController {
        public $helpers = array('Js' => array('Jquery'));
        public $components = array('RequestHandler');
        var $name = 'Products';

        function showProducts(){

            return 'This should to return in jQuery data';
        }
    }
?>

2 个答案:

答案 0 :(得分:3)

在cakePHP 2.x中,您的控制器需要以这种方式将json数据返回到$ .ajax请求:

<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');

class AjaxtestsController extends AppController {

function beforeFilter() {
        parent::beforeFilter();
    }

public function returnsSomthing()
    {
        $layout = 'ajax'; // you need to have a no html page, only the data.
        $this->autoRender = false; // no need to render the page, just plain data.
        $data = array();
        $jquerycallback = $_POST["callback"];
        //do something and then put in $data those things you want to return.
        //$data will be transformed to JSON or what you configure on the dataType.

        echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
    }

}

改善答案

您可以使用控制器的方法在db:find()上搜索数据,但我将搜索查询移到模型中:

首先:在模型代码中添加标记的行

App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---

第二:创建一个执行搜索的Model方法:

public function getdata(){
        $input = NULL; 
        $query = array();
        $sql = NULL;
        $data = array();
        $i = 0;

        $input = $_GET["name_startsWith"]; // <-- obtains the search parameter
        $input = Sanitize::clean($input); // <-- prepares the search parameter

        $sql = "select * from atable where condition like '".$input."%';";

        $query = $this->query($sql); // <-- the model execute the search

        if ($query){
            $c = count($query);
            for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
                $json['id'] = $query[$i][0]['id'];
                $json['column1'] = $query[$i][0]['column1'];
                $json['column2'] = $query[$i][0]['column2'];
                $data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
            }
        }
        $jquerycallback = $_GET["callback"];
        echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
    }

然后:在控制器上创建一个调用搜索的方法

public function getdata()
    {
        $layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
        $this->autoRender = false;  // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
        $this->Cliente->getclient(); // <-- Get the data
    }

你可以通过像这样的ajax调用这个方法:

$.ajax({
                url: "/application/controller/getdata",
                dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 10,
                        name_startsWith: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.search, function( item ) {
                            return {
                                value: item.id,
                                label: item.column1+" "+item.column2
                            }

                        }));

                    }
            });

检查以获取更多信息:

答案 1 :(得分:1)

错字行情不匹配

使用双引号括起来

url: "<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>",     
     ^                                                                                         ^

<小时/> 问题

url: '<?php echo Router::url(array('controller' => 'products',
                                          var ^ str^ var

controllerproducts被视为变量而不是字符串