使用Ajax和JSON进行jQuery UI自动完成

时间:2014-08-15 09:48:37

标签: jquery ajax json cakephp autocomplete

我试图用Ajax函数内部的JSON数据填充jQuery自动完成。这就是我的脚本:

<script>

$(function() {

$("#autocomplete").autocomplete({
    source: function(request, response)
    {
        $.ajax({
            url: "<?php echo $this->webroot;?>portfolios/ajax_clients_dropdown/"+request.term+".json",
            dataType: "jsonp"
      success: function(data)
            {
                response(data);
            }
        });
    }

  });
}); 

</script>

<label>Clients</label>
<div class = "ui-widget">
<input id = "autocomplete">
</div>

此代码用于在没有任何错误的情况下运行,但在搜索框中输入内容时不执行任何操作。它就像JSON不起作用。我试着摆弄它,但现在它给了我一个&#34;预期的标记&#39;}&#39;} &#34;错误。

此脚本位于我的视图文件中,并且url应指向我的控制器中的函数。如果我在浏览器中运行控制器功能,它会正确返回JSON数据。我有一个日志函数,一旦调用该函数就会运行。它在我直接在浏览器中运行时记录在日志中,但是当我正常运行网页时没有记录任何内容(从视图侧调用该函数)。

有人可以看一下吗?

1 个答案:

答案 0 :(得分:0)

在portfolioController里面的行动ajax_clients_dropdown把这个

public function ajax_clients_dropdown($model="portfolio") {
    $this->loadModel($model); // loadmodel let me use this action for multiple model
    $this->$model->recursive = -1;
    $this->autoRender = false;
    $this->layout = 'ajax';
    if ($this->request->is('ajax')) {
        $results = $this->$model->find('all', array('fields' => array('id','name'),
            'conditions' => array('name LIKE ' => '%'. $this->request->query['q'] . '%'),
        ));
        $return_arr= array();
        // you can change this loop with this 
        // $res = Hash::extract($results, '{n}.source'); // and change in your find condition 'name' with "name as label' cause in our script we will use the term "label"
        foreach ($results as $row) {
            $row_array['id'] = $row['source']['id'];
            $row_array['label'] = $row['source']['name'];

            array_push($return_arr,$row_array);
        }

        // echo json_encode($return_arr); WRONG!!!
        // THE TRICK IS HERE => add before your json the callback send by jquery and it will work!!!!
        $response = $this->request->query["callback"] . "(" . json_encode($return_arr) . ")";
        echo $response;
    }
}

在/Layout/ajax.ctp中输入此代码

<?php echo $this->fetch('content'); ?>

在你的默认布局之间并记得加载jquery和jqueryui

...
<?php
    echo $this->Html->script('jquery-1.11.1');
    echo $this->Html->script('jquery-migrate-1.2.1');
    echo $this->Html->script('jquery-ui/jquery-ui-1.10.4.min');
?>
...

并在您的视图中查看/ Portofolio / yourview.ctp尝试执行此类操作

<input id="tags" placeholder="your placeholder . bla bla bla">
</div>

<hr>
<input id="source_dest_id" type="hidden" name="source_dest_id" value=""/>


<script>
$(function(){
$( "#tags" ).autocomplete({

    source: function( request, response ) {
        $.ajax({
            url: "<?php echo $this->webroot;?>portfolios/ajax_clients_dropdown",
            dataType: "jsonp",
            data: {
                q: request.term
            },
            success: function( data ) {
                response( data );
            }
        });
        },
        minLength: 2,
        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        },
        focus: function(event, ui) {
        // prevent autocomplete from updating the textbox
            event.preventDefault();
        // manually update the textbox
            $(this).val(ui.item.label);
        },
        select: function(event, ui) {
        // prevent autocomplete from updating the textbox
            event.preventDefault();
        // manually update the textbox and hidden field
            $(this).val(ui.item.label);
            $("#source_dest_id").val(ui.item.id);
        }
        });

});

</script>

我希望这有帮助:)