2017-03-03 70 views
2

我試圖在輸入更改時向Laravel實時發佈輸入值,並返回一個包含所有與查詢匹配的數據的數組。但是,我總是收到一個空數組。我已經嘗試了很多東西來讓它工作,但沒有成功。Laravel在ajax發佈請求之後返回空字符串

控制檯說:

對象 級別: 「[]」 狀態:對象 :對象

匹配值在控制檯的值,則查詢不工作時,我改變$這個 - >鍵入數據庫中的字符串。所以問題的根源是$ request和$ request-> type,但我無法找到解決方案。

我會很感激所有的幫助,因爲我真的已經到了這個問題的最後。提前致謝。

$(document).ready(function() { 
 
     $("#question_type input").on('change', function postinput() { 
 
     var matchvalue = $(this).val(); // this.value 
 
     $.ajax({ 
 
      type: 'POST', 
 
      url: "{{route('get-levels')}}", 
 
      dataType: "json", 
 
      data: matchvalue 
 
     }).done(function(response) { 
 
      console.log(matchvalue); 
 
      console.log(response); 
 
      $('#question_type').append(response.levels); 
 
      console.log(response.levels); 
 
     }); 
 
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<fieldset class="form-group form_section" id="question_type"> 
 
    <h5>Selecteer in type vraag</h5> 
 
    <div class="form-check"> 
 
    <label class="form-check-label"> 
 
     <input class="form-check-input input" type="radio" name="type" id="exam" value="exam"> 
 
     Examenvraag 
 
    </label> 
 
    </div> 
 
    <div class="form-check"> 
 
    <label class="form-check-label"> 
 
     <input class="form-check-input input" type="radio" name="type" id="practice" value="practice"> 
 
     Oefenvraag 
 
    </label> 
 
    </div> 
 
</fieldset> 
 

 

 
ROUTE 
 

 
Route::post('/selectQuestion/selection/levels', '[email protected]')->name('get-levels')->middleware('auth'); 
 

 

 

 
CONTROLLER 
 

 
public function getLevels(Request $request){ 
 
     
 
\t \t $this->_type = $request->type; 
 
     
 
\t \t $levels = 
 
\t \t \t Question:: 
 
\t \t \t \t distinct() 
 
\t    ->where('type', $this->_type) 
 
\t    ->orderBy('level') 
 
\t    ->get(['level']); 
 

 
\t \t return response()->json(['levels' => strip_tags($levels), 'status' => $request]); 
 
\t }

+0

嘗試回聲json_encode([ '水平'=>用strip_tags($的水平), '狀態'=> $請求]); – Omi

+0

@omi同樣的結果不幸:( –

+0

)在您的jQuery中,ajax調用'data'需要位於鍵/值對字符串(查詢字符串)中,或者作爲Object /數組傳遞,然後通過jQuery轉換爲查詢字符串。意思是它應該像'type = yourvalue'。 –

回答

1

在JavaScript代碼的data屬性應該是:

data: { 'type': matchvalue } 

更改行:

$this->_type = $request->type; 

到:

$this->_type = $request->input('type'); 

驗證$this->_type是否具有從窗體捕獲的輸入。

您也可以嘗試改變你的查詢:

$levels = Question::distinct()->where('type', $this->_type)->orderBy('level')->get()->lists('level'); 
+0

這確實奏效!謝謝你,先生! –