Laravel - 将AJAX数据传递给函数

时间:2016-03-31 01:42:42

标签: php jquery ajax laravel laravel-5

我正在开发一个非常简单的Laravel应用程序,它基本上提供了一个基于id的图表。我相信我已经使用以下方式设置了正确的路线:

应用\ HTTP \ routes.php文件

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('getProcessorData', array('uses' => 'HonoursController@getProcessorData'));
#Route::get('getProcessorData/{id}', 'HonoursController@getProcessorData');
Route::get('getBandwidthData', array('uses' => 'HonoursController@getBandwidthData'));
Route::get('getMemoryData', array('uses' => 'HonoursController@getMemoryData'));

Route::resource('honours','HonoursController');

从那时起,我继续在控制器中设置正确的功能:

应用\ HTTP \控制器\ HonoursController.php

...
    public function getProcessorData()
    {
      $id = Input::get('host_id');
      return Response::json(HostProcessor::get_processor_formatted($id));
    }
...

由于这称为HostProcessor模型中的函数,我在下面创建了这个函数:

应用\ HostProcessor.php

...
    public static function get_processor_formatted($id)
    {
        $processor = self::findorfail($id);

        $json = array();
        $json['cols'] = array(
          array('label' => 'Time', 'type' => 'string'),
          array('label' => 'Kernel Space Usage', 'type' => 'number'),
          array('label' => 'User Space Usage', 'type' => 'number'),
          array('label' => 'IO Space Usage', 'type' => 'number')
        );

        foreach($processor as $p){
          $json['rows'][] = array('c' => array(
            array('v' => date("M-j H:i",strtotime($p->system_time))),
            array('v' => $p->kernel_space_time),
            array('v' => $p->user_space_time),
            array('v' => $p->io_space_time)
          ));
        }

        return $json;
    }
...

最后我设置了我的AJAX函数,如下所示:

资源/视图/荣誉/分音/ master.blade.php

...
     <script type="text/javascript">
        // Load the Visualization API and the piechart package.
        google.charts.load('current', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
           var processor_usage = $.ajax({
              url:'getProcessorData',
              dataType:'json',
              async: false
           }).responseText;

           var p_options = {
              title: 'Processor Usage',
              width: 800,
              height: 400,
              hAxis: {
                 title: 'Time',
                 gridlines: {
                    count: 5 
                 }
              } 
          };
...

现在我遇到的问题是当我尝试将值传递给HostProcessor函数时,它失败了。我尝试使用AJAX的data属性传递id值。通过这样做,我不得不更新到Route::get('getProcessorData?{id}', array('uses' => 'HonoursController@getProcessorData'));的路由,但这仍然失败,出现404错误。我还尝试使用$id = Input::get('host_id');获取host_id值的值并将其传递给HostProcessor函数,但仍然因404错误而失败。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

// app\Http\routes.php
Route::get('getProcessorData/{id}', 'HonoursController@getProcessorData');

// app\Http\Controllers\HonoursController.php
//...
public function getProcessorData($id)
    {

      try {

          $processor = HostProcessor::get_processor_formatted($id);

          return response()->json($processor, 200);

      } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

          return response()->json(['error' => $e->getMessage()], 404);

      } catch(\Exception $e) {

          return response()->json(['error' => $e->getMessage()], 500);
      }

    }
//...