javascript - 从 PHP 转换为 JSON 文件

标签 javascript php json laravel

我是 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 the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

$array = ['data'];
return response()->json($array);

Laravel Documentation (json-response)

关于javascript - 从 PHP 转换为 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428126/

相关文章:

javascript - 具有动态宽度和高度元素的 Jquery Masonry

javascript - 使用由日期触发的 style.display

javascript - iFrame 之间的通信?

php - MySql - 如何对两列中两个值的组合创建唯一约束

java - 有效 json 字符串上的 org.json.JSONObject 异常

java - 如何使用json节点解析json数组值

javascript - ES6 类型来表示一个可以反转的键值对象

php - 尽管格式正确,MySQL 字段 DATETIME 仍被截断

php - 如何在 DSN 中指定用户名和密码?

javascript - 运行一个 json 字符串函数