【问题标题】:jQuery UI Autocomplete with Ajax and JSON使用 Ajax 和 JSON 的 jQuery UI 自动完成
【发布时间】:2014-10-09 01:43:41
【问题描述】:

我正在尝试使用 Ajax 函数内部的 JSON 数据填充 jQuery Autocomplete。这是我的脚本的样子:

<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 不工作一样。我试着摆弄它,但现在它给了我一个“预期的令牌'}'”错误。

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

有人可以看看吗?

【问题讨论】:

  • 尝试将 $this-&gt;response-&gt;type('application/json'); 放入 JSON 的控制器操作中。
  • 我对代码和结果做了更多检查。我发现我的请求被发送了,并且 JSON 数据实际上被返回了,但由于某种原因它没有显示在我的自动完成中。

标签: jquery ajax json cakephp autocomplete


【解决方案1】:

在投资组合控制器中的行动 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');
?>
...

在你看来 View/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>

希望对你有所帮助:)

【讨论】:

    猜你喜欢
    • 2012-08-04
    • 1970-01-01
    • 2014-11-22
    • 2018-01-18
    • 1970-01-01
    • 2012-07-11
    • 2012-04-23
    • 2016-11-16
    • 1970-01-01
    相关资源
    最近更新 更多