如何在Laravel 5.4中使用setInterval进行AJAX [英] How to do AJAX with setInterval in Laravel 5.4

查看:83
本文介绍了如何在Laravel 5.4中使用setInterval进行AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在普通的PHP中,我可以执行AJAX并使用setInterval更新页面,如下所示:

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

script.js

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

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

在Laravel 5.4中,我不知道该怎么做了.使用Controllers和Views,传递数据似乎很复杂.

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

script.js

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

路线

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

我当时想通过从$.ajax调用url: "/fetch-data"会将json数据作为响应,但是相反,它向我显示了整个html页面,这不是我想要的.

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.

任何有关如何在Laravel 5.4中实现这一点的想法都将受到赞赏.

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

推荐答案

您快到了;只是您返回的格式错误:

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

代替

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

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

这篇关于如何在Laravel 5.4中使用setInterval进行AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆