CakePHP 3自动完成AJAX响应

时间:2017-07-03 22:27:14

标签: php jquery html ajax cakephp

我一直试图让cakephp建议来自我的表格的数据输入,比如自动完成。我已经做了一些关于其他人如何做到这一点的阅读,但仍然无法弄明白。目前似乎每次我的控制器都在等待ajax请求时它总是错误的。有些错误来自控制台,我不知道我做错了什么。我尝试删除if($ this-> request-> is('ajax'))语句,但后来我得到一个错误,它无法发出标头。 这是我在InvoicesController中的搜索功能,我从其他人的例子中获取了代码,但未能实现它。

     public function search()
{
    if ($this->request->is('ajax')) {
        $this->autoRender = false;
        pr('b');
        $name = $this->request->query['term'];
        $results = $this->Invoices->find('all', [
            'conditions' => [ 'OR' => [
                'id LIKE' => $id . '%',
            ]]
        ]);
        $resultsArr = [];
        foreach ($results as $result) {
             $resultsArr[] =['label' => $result['full_name'], 'value' => $result['id']];
        }
        echo json_encode($resultsArr);
    }
}

这是我的search.ctp

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

    <?php echo $this->Form->input('id', ['type' => 'text']);?>
<script>
    jQuery('#id').autocomplete({
        source:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>',
        minLength: 1
    });
</script>

这是我的发票表,我想根据用户输入的内容建议ID。 invoices Table

1 个答案:

答案 0 :(得分:2)

我可能没有看到您的确切问题,但让我指出一些我认为可能有助于此问题的事情。

删除此行。没有必要

$this->autoRender = false;

相反,你应该在最后这样做。请参阅使用RequestHandler

$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');

这将返回没有根密钥的数据

 [
   {"label":"Label Value"}, 
   {"label":"Another Label Value"}
 ]

或者你可以这样做

$this->set('_serialize', ['resultsArr']);

这将返回

之类的数据
{"resultArr":[
   {"label":"Label Value"}, 
   {"label":"Another Value"}
]}

用此替换您的查找器查询。

$resultArr = $this->Invoices->find('all')
    ->where(['id LIKE' => $id . '%'])
    // If you want to remap your data use map
    // All queries are collections
    ->map(function ($invoice) {
        return ['label' => $invoice->full_name, 'id' => $invoice->id];
    });

在我看来,你可能想要回顾一下新的cakephp 3 orm。编写这些文档需要付出很多努力才能轻松阅读和相关。我不是一个向人们推送文档的人,但它会为你节省数小时的挫折感。

Cakephp 3 ORM documentation

我注意到的一些小事也是问题。

  • 你永远不会定义$ id。
  • 您定义$ name但从不使用它。
  • pr是一个调试语句,我不知道你为什么要这样做。

根据您的评论,这是ajax检测的更新。

// By default the ajax detection is limited to the x-request-with header
// I didn't want to have to set that for every ajax request
// So I overrode that with the accepts header.
// Any request where Accept is application/json the system will assume it is an ajax request
$this->request->addDetector('ajax', function ($request) {
    $acceptHeaders = explode(',', $request->env('HTTP_ACCEPT'));

    return in_array('application/json', $acceptHeaders);
});