我是 Laravel 学习者。我现在想要学习的是将一个 JSON
文件从后端发送到前端,以便我将使用这个 JSON
文件来绘制图表。
在我的模型中,我编写了一个函数来提取值和时间戳created_at
。这是一段代码,它将返回与单个网站和时间戳相关的谷歌页面速度值。然后我想使用 JS
绘制图表,其中垂直值是谷歌页面速度水平方向是创建于
的时间戳。
谁能帮帮我?我需要将返回值更改为数组吗?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notification;
use App\Status;
class ChartController extends Controller
{
public function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// return an empty json array instead of false
//return false;
return response()->json(array());
}
}
路线是
路线::get('json','ChartController@speedHistory');
一直提示方法未定义。这是我的模型 通知类扩展模型 { protected $fillable = ['id','website_url','email','slack_channel','check_Frequency','alert_Frequency','speed_Frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
最佳答案
您可以在 response()
上使用 json()
方法。
The
json
method will automatically set theContent-Type
header toapplication/json
, as well as convert the given array to JSON using thejson_encode
PHP function:
$array = ['data'];
return response()->json($array);
关于javascript - 从 PHP 转换为 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428126/