如何在Laravel 5.4中使用setInterval进行AJAX [英] How to do AJAX with setInterval in Laravel 5.4
问题描述
在普通的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屋!