cakePhp中的Ajax自动完成 - 网络错误:404未找到

时间:2012-04-09 11:55:34

标签: javascript ajax cakephp jquery

我试图通过在我的视图页面中使用jquery UI库(jquery autocomplete)来根据用户输入获取部门名称来进行ajax调用。自动完成功能看起来像

$( "#auto_complete" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url:  "/employees/getAddress",
                dataType: "jsonp",
                data: {
                    featureClass: "P",
                    style: "full",
                    maxRows: 12,
                    name_startsWith: request.term
                },
                success: function( data ) {

                    response( $.map( data.geonames, function( item ) {
                        return {
                            label: item.name,
                            value: item.id
                        }
                    }));
                }
            });
        },
        minLength: 2,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.label :
                "Nothing selected, input was " + this.value);
        },
        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }
    });

这里我正在调用一个名为getAddress()

的动作

看起来像

       class EmployeesController extends AppController {

//var $components = array('Autocomplete');
public $components = array('RequestHandler');
var $helpers = array('Javascript', 'Ajax');
    /**
     * index method
     *
     * @return void
     */
    //var $helpers = array('Ajax');
 public function getAddress() {
        $this->log($this->params, 'debug');
        $this->layout = 'ajax';
        $departments = $this->Department->find('all', array(
        'conditions'=>array('Department.name LIKE'=>$this->params['url']['q'].'%'),
        'fields'=>array('name', 'id')));
        $this->log($departments, 'debug');
        //$this->set('departments', $departments);
        $this->set(compact('departments'));
}

但无论何时我正在进行ajax通话我都会收到错误

“NetworkError:404 Not Found - http://localhost/employees/getAddress?callback=jQuery1710012251482368207167_1333972423088&featureClass=P&style=full&maxRows=12&name_startsWith=sal&_=1333972426249

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我猜你错过了url中的项目文件夹,试试:


var webroot = '<?php echo $this->webroot; ?>';
$( "#auto_complete" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url:  webroot + "employees/getAddress",
                dataType: "jsonp",
                data: {
                ......

或者您可以在layouts / default.ctp中定义webroot并使用它