2017-02-09 26 views
0

我想要做一個帳單結構,我可以選擇一個客戶端,下一個選擇窗體將向我顯示客戶端的所有項目,但出於某種原因,我正在麻煩與此。在刀片視圖中檢索JSON響應 - Laravel 5.3

這是我route.php

Route::resource('bills', 'BillsController'); 
Route::get('bills/items','[email protected]'); 

這是我BillsController

private function items($request) { 
    try { 
     if ($request) { 
      $id = $request->client_id; 
      $items = Item::where('client_id', $id)->get()->pluck('code', 'id'); 

      return redirect()->json($items); 
     } else { 
      \Session::flash('error_message', 'Ups! Hemos tenido un error.'); 
      return redirect()->back(); 
     } 
    } catch (Exception $e) { 
     \Session::flash('error_message', 'Ups! Hemos tenido un error.'); 
      return redirect()->back(); 
    } 
} 

這是我的刀片視圖中查看腳本:

<script> 
$(document).ready(function() { 

    $('#clients').change(function() { 
     var $client_id = $('#clients').val(); 
     console.log($client_id); 
     var $url = '{{ url('MyAdmin/bills/items') }}'; 
     console.log($url); 
     $.getJSON($url, {'client_id': $client_id}, function(resp) { 
      console.log(resp); //For some reason here the "resp" is not working 
      $.each(resp, function(key, answer) { 
       $('#items').append('<option value="'+answer.id+'">'+answer.code+'</option>'); 
      }); 
     }); 
    }); 
}); 

任何想法?非常感謝!

回答

0

這是因爲它實際上進入} catch (\Exception $e)。但是你也沒有在這裏返回JSON響應。你正在重定向。

問題是redirect()對象不包含->json()方法,但response()對象。所以,改變它:

return response()->json($items); 

而且,在你的錯誤處理程序,返回響應時一個422錯誤代碼,因此它西港島線觸發你的諾言了.error()

return response(422)->json([$e->getMessage()]); 
+0

我剛試過,不工作:( –

+0

@CarlosOrtega直接在瀏覽器中訪問鏈接後會發生什麼 – Ohgodwhy

+0

'ReflectionException在Route.php行333:?方法應用\ HTTP \控制器\後端\ BillsController: :show()does not exist'我得到這個 –