2017-03-03 110 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

这确实奏效!谢谢你,先生! –