【问题标题】:jQuery autocomplete not displaying values Cakephp routejQuery自动完成不显示值Cakephp路由
【发布时间】:2017-07-06 10:05:21
【问题描述】:

我正在尝试使用 jQuery 自动完成在 Cakephp 中显示我的表中的数据。我可以使用标签自动完成工作,但无法显示表格中的数据。在表中搜索类似数据以正确返回的函数,但我不完全确定它是否正确地将其传递给自动完成脚本。我对此还是很陌生。

这是我在 InvoicesController.php 中的搜索功能

public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax')) 
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result) 
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);


    }
}

这是我 search.ctp 中的代码

<?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = '<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>'
    jQuery('#id').autocomplete({
        source: tags,
        minLength: 1
    });
</script>

这是函数返回的内容以及自动完成下拉菜单中显示的内容。

这就是使用 testTags 数组时的样子

视图在源代码中的样子。

<div class="input text"><label for="id">Id</label><input type="text" name="id" id="id"/></div>
<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = '/invoices/search'
    jQuery('#id').autocomplete({
        source: testTags,
        minLength: 1
    });
</script>    </div>

【问题讨论】:

    标签: javascript php jquery cakephp autocomplete


    【解决方案1】:
        <?php use Cake\Routing\Router; ?>
    
        <?php echo $this->Form->input('id', ['type' => 'text']); ?>
    
    <script>
        var testTags = ['52332', '56346', '5734'];
        var tags = $.post(url:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>');
        jQuery('#id').autocomplete({
            source: tags,
            minLength: 1
        });
    </script>
    

    尝试使用 Jquery $.post 或 $.get 通过 ajax 获取数据

    【讨论】:

    • jQuery('#id').autocomplete({ source: $.post(url:'/invoices/search'), minLength: 1 });这给出了该输出,但在参数列表之后给出了错误“Uncaught SyntaxError: missing )”
    • 是的,在使用 Jquery $post 函数时,我的代码有错误。好的语法是这样的:$.post( "url", { parameter1: "test", parameter2: "something" }) .done(function( data ) { //Do something with the data you receive from the backend });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    相关资源
    最近更新 更多