Javascript 从PHP转换为JSON文件

Javascript 从PHP转换为JSON文件,javascript,php,json,laravel,Javascript,Php,Json,Laravel,我是一个拉威尔的学习者。我现在试图学习的是将一个JSON文件从后端发送到前端,这样我将使用这个JSON文件绘制一个图形 在我的模型中,我编写了一个函数,该函数将提取创建时的值和时间戳。下面是一段代码,它将返回与单个网站关联的google页面速度值和时间戳。然后我想使用JS绘制一个图表,其中垂直值是google页面速度,水平值是在创建的时间戳 有人能帮我吗?是否需要将返回值更改为数组 namespace App\Http\Controllers; use Illuminate\Http\Requ

我是一个拉威尔的学习者。我现在试图学习的是将一个JSON文件从后端发送到前端,这样我将使用这个JSON文件绘制一个图形

在我的模型中,我编写了一个函数,该函数将提取创建时的值和时间戳。下面是一段代码,它将返回与单个网站关联的google页面速度值和时间戳。然后我想使用JS绘制一个图表,其中垂直值是google页面速度,水平值是在创建的时间戳

有人能帮我吗?是否需要将返回值更改为数组

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

路由::获取'json','ChartController@speedHistory';

不断抱怨没有定义方法。这是我的模型
lass通知扩展模型 { 受保护的$fillable=['id'、'WEBITE_url'、'email'、'slack_channel'、'check_frequency'、'alert_frequency'、'speed_frequency'、'active']

public function statuses(){
    return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
试试这个

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

为了改进我的回答,您需要返回'response->json',这将把内容类型更改为json,本质上使响应成为所谓的json文件

你能试试这个吗?我想你是在试图从一个不应该工作的集合中获取值和创建值。我假设你使用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());
}
更新:添加了通知::基于您函数中op的注释:

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);
    }
在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 );
});
您可以在响应时使用json方法

json方法将自动将内容类型头设置为application/json,并使用json_encode PHP函数将给定数组转换为json:

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

L4返回响应::json$data\u数组、$status\u代码;或L5返回响应->json$data\u数组、$status\u代码;您能解释一下$o\u响应->值部分吗?如果我没有弄错,$o\u响应应该是一个数组,并且您不能调用数组上的对象属性。请尝试将$o\u响应查询从->get to->first@devk:$o\u响应->值,对吗这是一个数组。一个网站可能有不同的谷歌页面速度,例如70,80100等,它作为值存储在pivot表中,我将其提取为$o_response->values。我认为标题仍然是text/html而不是application/json。使用laravel的response对象是advisableit看起来很酷,但很抱歉有一个问题在我的laravel模型中有你的代码,然后我为它做了一个路由{route::get'json','controller@json'}。我认为路径必须通过控制器。我在哪里堆栈?在控制器中写入什么,以便我可以将数据传递到另一个页面并进一步使用JS?您可能希望在控制器中写入此方法,而不是在模型中写入此方法。我不知道您的模型被调用,但将$this->status更改为您的模型name是必需的。如果您的模型名为History,那么您可以执行History::where'status\u id',$o\u status->id。将此方法放入控制器将返回json数据,以便您可以将其与javascript代码一起使用。我做了与您建议的相同的事情。我为其创建了一个控制器和一个路由。但它抱怨我有一个方法在名为statuses的模型中,它抱怨它可以找到方法。我更新了代码。在您的模型中,您需要添加类似以下公共函数状态的内容{return$this->belongsTo'App\themodelyuaretryingtofetch';}类通知扩展模型{protected$filleble=['id'、'website_url'、'email'、'slack_channel'、'check_frequency'、'alert_frequency'、'speed_frequency'、'active'];公共功能状态{return$this->belongsToMany'App\Status'->带Pivot'values'->带时间戳;}@保罗·科斯塔:遵循你的想法似乎很酷。不过我有一个问题。speedHistory函数在模型中,我有一个路由{route::get'json',controller@json},我想,这不是拉威尔的工作方式吗?要使路线工作,应该有一个控制器?现在的问题是在控制器中写入什么。或者我必须在控制器中写入speedHistory函数吗?在路线文件中使用:route::get'name_route',SpeedController@speedHistory以及您的ajax url:/name\u路由