【问题标题】:convert from PHP to JSON file从 PHP 转换为 JSON 文件
【发布时间】:2023-03-09 20:10:01
【问题描述】:

我是 Laravel 学习者。我现在想学的是从后端发送一个JSON文件到前端,这样我就可以用这个JSON文件来画图了。

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

谁能帮帮我?是否需要将返回值改为数组?

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

路线是

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

一直抱怨方法未定义。这是我的模型 las 通知扩展模型 { 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();
}

【问题讨论】:

  • L4 return Response::json($data_array, $status_code); 或 L5 return response()->json($data_array, $status_code);
  • 您能解释一下$o_response->values 部分吗?如果我没记错的话 $o_reponse 应该是一个数组,你不能在数组上调用对象属性。尝试将 $o_reponse 查询从 ->get() 更改为 ->first()
  • @devk : $o_response->values ,没错,它是一个数组。一个网站可能有不同的谷歌页面速度,例如 70,80,100 等,它作为值存储在数据透视表中,我将其提取为 $o_response->values。

标签: javascript php json laravel


【解决方案1】:

试试这个

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

【讨论】:

  • 我认为标题仍将是 text/html 而不是 application/json。建议使用 laravel 的 Response 对象
【解决方案2】:

为了改进我的回答,您需要返回“response()->json()”,这会将内容类型更改为 json,本质上使响应成为所谓的“JSON 文件”。

你可以试试这个吗?我认为您正在尝试从不应工作的集合中获取值和 created_at 。我假设您使用 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());
}

更新:添加了 Notification:: 基于 op 的 cmets

【讨论】:

  • 这看起来很酷,但很抱歉有一个问题。我在 laravel 的模型中编写你的代码。然后我为它做了一条路线 {Route::get('json','controller@json'}我可以将数据传递到另一个页面并使用 JS 进一步工作?
  • 您可能希望在控制器而不是模型中编写此方法。我不知道您的模型叫什么,但需要将 $this->statuses() 更改为您的模型名称。如果您的模型称为 History,那么您可以执行 History::where('status_id', $o_status->id)。将此方法放在控制器中将返回 json 数据,以便您可以将其与您的 javascript 代码一起使用。
  • 我已经按照你的建议做了同样的事情。我为它创建了一个控制器和一个路由。但它抱怨我在模型中有一个名为 statuses 的方法,它抱怨它可以找到该方法。我更新了我的代码。
  • 在您的模型中,您需要添加类似以下的内容 public function statuses() { return $this->belongsTo('App\TheModelYouAreTryingToFetch'); }
  • lass Notification extends Model { 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(); }
【解决方案3】:

在你的函数中:

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

【讨论】:

  • @Paulo Costa:听从你的想法似乎很酷。我有一个问题。 speedHistory 函数在模型中,我有一条路线{ Route::get('json',controller@json},我想,这不是它在 laravel 中的工作方式吗?为了工作路线应该有一个控制器?现在的问题是在控制器中写什么。还是我必须将 speedHistory 函数放入控制器中?
  • 你在路由文件中使用:Route::get('name_route', SpeedController@speedHistory) 和你的ajax url:/name_route
【解决方案4】:

您可以在response() 上使用json() 方法。

json 方法会自动将Content-Type 标头设置为application/json,并使用json_encode PHP 函数将给定数组转换为JSON:

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

Laravel Documentation (json-response)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2020-09-21
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多