简体   繁体   English

从PHP转换为JSON文件

[英]convert from PHP to JSON file

I am a Laravel learner. 我是Laravel学习者。 What I am trying to learn now is to send a JSON file from a back end into the front-end, so that I will use this JSON file to draw a graph. 我现在要学习的是将JSON文件从后端发送到前端,以便我将使用此JSON文件绘制图形。

In my model, I write a function that will extract the values and time stamp created_at . 在我的模型中,我编写了一个函数,该函数将提取值和时间戳created_at Here is a piece of code that will return the google page speed value associated with a single website and the time stamp.then I want to use JS to draw the graph where the vertical value is the google page speed and the horizontal is the time stamp created at . 这是一段代码,将返回与单个网站相关的Google页面速​​度值和时间戳。然后我想使用JS绘制图形,其中垂直值为Google页面速​​度,水平值为时间戳created at

Anyone who can help me? 谁能帮助我? Do I need to change the return value to an array? 我需要将返回值更改为数组吗?

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());
    }
}

and trhe route is 路线是

Route::get('json','ChartController@speedHistory'); 路线:: get('json','ChartController @ speedHistory');

keeps complaining the methods is not defined. 一直抱怨方法未定义。 this is my model lass Notification extends Model { protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active']; 这是我的模型。通知扩展了模型{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();
}

To improve on my answer, you will need to return 'response()->json()' which will change the content type to json, essentially making the response a so called "JSON file". 为了改善我的答案,您将需要返回'response()-> json()',它将内容类型更改为json,本质上使响应成为所谓的“ JSON文件”。

Can you try this? 你可以试试这个吗? I think you are trying to get values and created_at from a collection which should not work. 我认为您正在尝试从不起作用的集合中获取值和created_at。 I assume you use L5, see Danis Abols comment otherwise. 我假设您使用L5,否则请参见Danis Abols的评论。

public function speedHistory(){
    $o_status = Status::where('name','speed')->first();
    $o_response = Notification::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);
    }
// I would return an empty json array instead of false
//return false;
return response()->json(array());
}

Update: added Notification:: based on comments from op 更新:添加了通知::基于op的评论

In your function: 在您的职能:

public function speedHistory(){

 try{ 

       $o_speed = Status::where('name','speed')->first();
       $o_response = $this->statuses()->where('status_id', $o_status->id)
    ->select('values', 'created_at')->orderBy('created_at','DESC')->get();

       if($o_response === null)
//You can use this to go in catch: "throw new Exception();" or "return false" if you want
              throw new Exception();

      // Returns a json to be consumed in ajax
      return response()->json(['status' => 1, 'code' => 200, 'message' => 'Your message', 'value' => $o_response->values, 'timestamp' => $o_response->created_at], 200);
    }catch(\Exception $e){
      return response()->json(['status' => 0, 'code' => 400, 'message' => $e->getMessage()], 400);
    }

In your ajax you consume this way: 在您的ajax中,您将使用以下方式:

var request = $.ajax({
// Here's your route of speedHistory
  url: "YOUR_ROUTE",
  type: "GET",
  dataType: "json"
});

request.done(function(response) {
    if(response.status == '1'){
         $("#youDiv").html(response.value + ' - ' + response.timestamp);
     }
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

You could use the json() method on response() . 您可以在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: json方法将自动将Content-Type标头设置为application/json ,并使用json_encode PHP函数将给定数组转换为JSON:

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

Laravel Documentation (json-response) Laravel文档(json-响应)

尝试这个

return json_encode(array('value' => $o_response->values,'timestamp' => $o_response->created_at));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM