1

我正在尝试向控制器发送 ajax 请求,它应该返回一些东西,但不是。我的元素(视图/元素/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';
        }
    }
?>
4

2 回答 2

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
                            }

                        }));

                    }
            });

检查此以获取更多信息:

于 2013-11-12T20:00:53.950 回答
1

错别字引号不匹配

使用双引号来换行

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


问题

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

controller并被products视为变量而不是字符串

于 2013-11-11T16:54:30.520 回答