2016-04-02 28 views
0

vue-resourceというプラグインでvuejs ajaxコールを使用してデータベースからデータを取得しようとしています。残念ながら、jsonデータオブジェクトにはhtmlページが含まれていて、データベースの実際のデータは含まれていません。誰かが間違っていることを教えてもらえますか?Vuejs ajax Laravel 5.1ブレードテンプレートでデータを返さないGETリクエスト

<?php 
Route::get('find', '[email protected]'); 

fruitsctrl.php(コントローラ)

routes.phpの

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use App\Fruit; 
use App\Http\Requests; 
use App\Http\Controllers\Controller; 

class FruitsCtrl extends Controller 
{ 
    public function index(Request $req){ 
     $fruits = Fruit::all(); 
     return view('fruitsHome', $fruits); 
    } 
} 

fruit.php(モデル)

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Fruit extends Model 
{ 
    protected $fillable = [ 
      'id', 'name', 'type' 
    ]; 
} 

fruitshome.blade: これは私のコードです。 PHP(表示)

<head> 
     <meta id="token" content="{{ csrf_token() }}"> 
</head> 
<body> 
    <div class="row" id="vapp"> 
     <ul> 
      <li v-for="fruit in fruits"> 
       @{{ fruit.name }} 
       @{{ fruit.type }} 

      </li> 
     </ul> 
    </div> 
<body> 

app.js(ジャバスクリプト)

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content'); 
var v = new Vue({ 
    el : "#vapp", 
    ready :function() { 
     this.fetchFruits(); 
    }, 
    data : { 
     fruit : {id:'', name:'', type:''}, 
     fruits : [] 
    }, 
    methods : { 
     fetchFruits : function(){ 
      this.$http.get('/find').then(function(res){ 
       this.fruits = res; 
      },function (data){ 
       console.log(error ...); 
      }); 
     } 
    } 
}); 

答えて

0

私はあなたがこのようなモデルでは、テーブル名を設定する必要があると思う:

class Fruit extends Model 
{ 

    protected $table = 'fruits'; 
    protected $fillable = [ 
     'id', 'name', 'type' 
    ]; 
} 

ます。また、このようなインデックスメソッドを更新する必要があります。

public function index(Request $req){ 
    $fruits = Fruit::all(); 
    return view('fruitsHome')->withFruits($fruits); 
} 

最後にブレードを更新します。

 <li v-for="fruits in fruit"> 
      @{!! $fruits->name !!} 
      @{!! $fruits->type !!} 

     </li> 

それはあなたが現在お使いのコントローラからビューを返している

+0

ご返信ありがとうございます。私はあなたの提案を試みましたが、うまくいきません。私はilluminate \ View \ View.phpでエラー例外を受け取りました。エラーは不正なオフセットタイプです... – DBoonz

1

場合に役立ちます私に教えてください:、あなたが直接雄弁な結果を返すことができる代わりに

class FruitsCtrl extends Controller 
{ 
    public function index(Request $req){ 
     $fruits = Fruit::all(); 
     return view('fruitsHome', $fruits); 
    } 
} 

を、彼らはのように出力されますJSON:

class FruitsCtrl extends Controller 
{ 
    public function index(Request $req){ 
     $fruits = Fruit::all(); 
     return $fruits; 
    } 
} 
関連する問題