2017-01-02 125 views
1

我是Laravel的學習者。我現在試圖學習的是將JSON文件從後端發送到前端,以便我使用這個JSON文件繪製圖形。從PHP轉換爲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()); 
    } 
} 

和trhe路線

路線::得到( 'JSON', 'ChartController @ speedHistory');

不斷抱怨方法沒有定義。這是我的模型 lass Notification擴展模型 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(); 
} 
+2

L4'返回響應:: json($ data_array,$ status_code);'或L5'return response() - > json($ data_array,$ status_code);' – Peon

+0

您能解釋一下'$ o_response->的值s'部分?如果我沒有弄錯,$ o_reponse應該是一個數組,你不能在數組上調用對象屬性。嘗試將$ o_reponse查詢從' - > get()'更改爲' - > first()' – devk

+0

@ devk:$ o_response-> values,它是一個數組。一個網站可能有不同的谷歌頁面速度,例如70,80,100等,它存儲在數據透視表中的值,我提取它作爲$ o_response->值。 –

回答

-1

試試這個

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

我認爲頭文件仍然是'text/html'而不是'application/json'。使用laravel的'Response'對象是可取的 –

0

爲了改善我的答案,你將需要返回的迴應() - > 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()); 
} 

更新:補充通知::基於從運算

+0

似乎很酷,但是很抱歉有一個問題。我在laravel的模型中寫下你的代碼。然後我爲它做了一個路由{Route :: get('json','controller @ json'}。我認爲Route必須經過控制器,在這裏我要堆棧?在控制器中寫什麼,我可以將數據傳遞到另一個頁面,並進一步與JS工作? –

+0

你可能會想要在你的控制器而不是你的模型中寫這個方法我不知道你的模型叫什麼,但改變$ this-> statuses()到你的如果您的模型名爲History,那麼您可以執行History :: where('status_id',$ o_status-> id)。將此方法放在控制器中將返回json數據,以便您可以將其與你的javascript代碼 – Matkey

+0

我已經做了同樣的事情,因爲你建議我創建了一個控制器和路由它,但它抱怨說我有一個方法在模型中稱爲狀態,它抱怨說它可以找到方法。我的代碼 –

0

評論在您的函數:

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

你應該解釋爲什麼這解決了這個問題。 –

+0

@Paulo Costa:按照你的想法看起來很酷。我有一個問題,但。 speedHistory函數在模型中,我有一個路線{Route :: get('json',controller @ json},我想,是不是它在laravel中工作的方式?對於工作路線應該有一個控制器?現在的問題是在控制器中寫什麼,或者我是否需要將速度歷史功能添加到控制器中? –

+0

您在路徑文件中使用: Route :: get('name_route',SpeedController @ speedHistory) 和您的ajax網址: /name_route –

0

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

json方法將Content-Type頭自動設置爲application/json,以及使用json_encode PHP函數給定的數組轉換成JSON:

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

Laravel Documentation (json-response)