[英]Vuejs ajax GET request not returning data in Laravel 5.1 Blade template
我正在嘗試通過vuejs ajax調用和名為vue-resource的插件從數據庫中檢索數據。 不幸的是,json數據對象包含html頁面,而不包含數據庫中的實際數據。 有人可以告訴我做錯了什么嗎? 這是我的代碼:
routes.php
<?php
Route::get('find', 'FruitsCtrl@index');
fruitctrl.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(javascript)
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 ...);
});
}
}
});
您當前正在從控制器返回視圖:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome', $fruits);
}
}
相反,您可以直接返回Eloquent結果,它們將以JSON輸出:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return $fruits;
}
}
我認為您需要像這樣在模型中設置表名稱:
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>
讓我知道是否對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.