How to do AJAX with setInterval in Laravel 5.4

2019-09-18 09:12发布

问题:

In normal PHP, I can do AJAX and update the page with setInterval as follows:

script.js

setInterval(function(){
    $.get( "fetch_json.php", function( data ) {
    var jsonData = JSON.parse(data);
    $.each(jsonData, function(itemKey,itemObject){
        // update div without refreshing the page
    }
},1000);

fetch_json.php

$results_array = [];
$file = new SplFileObject("file.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    $results_array[] = $row[0];
    $results_array[] = $row[1];
    $results_array[] = $row[2];
    $results_array[] = $row[3];
}
echo json_encode($results_array);

In Laravel 5.4, I dont know how to do this anymore. With Controllers and Views, passing data seems complicated.

I've tried doing the following in my Controller:

class PageController extends Controller
{
    public function fetchData()
    {
        $results_array = [];
        $file = new \SplFileObject("file.csv");
        $file->setFlags(\SplFileObject::READ_CSV);
        foreach ($file as $row) {
            $results_array[] = $row[0];
            $results_array[] = $row[1];
            $results_array[] = $row[2];
            $results_array[] = $row[3];
        }
     $json = json_encode($results_array);
     return view('page',['json'=>$json]);
    }
}

script.js

$(document).ready(function(){
setInterval(function(){
    $.ajax({
      url: "/fetch-data",
      success: function( response ) {
        // update div
      }
    });
},1000);
});

Routes

Route::get('/fetch-data', 'PageController@fetchData');

I was thinking that by calling url: "/fetch-data" from $.ajax will spit the json data as a response but instead, its showing me the whole html page which is not what I want.

For simple routing and passing data back to view, its fine. but updating the view every couple of seconds to update the contents without refreshing the page... it seems very complicated.

Any ideas on how I can implement this in Laravel 5.4 is greatly appreciated.

回答1:

You are almost there; just you are returning it the wrong format:

instead of

return view('page',['json'=>$json]);

do

return response()->json($results_array);


标签: php laravel-5