2017-07-03 123 views
0

我一直試圖讓cakephp建議從我的表中提取數據,如自動完成。我已經做了一些關於其他人如何做到這一點的解讀,但仍然無法弄清楚。目前看來,每當我的控制器正在等待一個Ajax請求並且它總是假的。控制檯沒有出現錯誤,我不確定我做錯了什麼。我嘗試刪除if($ this-> request-> is('ajax'))語句,但後來發現有關它的錯誤無法發出標題。 這是我在InvoicesController中的搜索功能,我從別人的例子中獲取代碼但未能實現它。CakePHP 3自動完成AJAX響應

 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

我可能不是看到你確切的問題,而是讓我指出我看到的可能有助於解決這個問題的一些事情。

刪除此行。這是沒有必要的

$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"} 
]} 

Repl用你的發現者查詢。

$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); 
}); 
+0

謝謝我將閱讀文檔,我做了這些更改,但我相信我的search.ctp沒有正確發送數據,因爲我認爲它實際上並沒有超過is( 'ajax')在控制器中。這就是爲什麼我試圖使用公關來看看它是否曾經在那裏。 –

+0

@ mark.nz - 我更新了我的答案以及如何檢測ajax。 – styks

+0

我會在哪裏放置新的ajax檢測代碼? –