【发布时间】:2018-09-19 13:52:22
【问题描述】:
如何在 laravel 中获取实时数据?
逻辑
我有基于 JavaScript 的表单,用于在我的数据库中保存新数据并且它正在工作
在我的保存数据表单旁边,我有一个选择框,其中包含要选择的我保存的数据。
问题出在我的选择框中,我只能看到旧数据,如果我想查看刚刚保存的数据,我必须刷新页面。
示例:
我将新规范保存在我的数据库中,比如说 core i5 cpu 然后在我的表单旁边我有选择框来选择该框中的规范我看不到 core i5 cpu 我必须刷新页面才能看到它。
问题
如何在不刷新页面的情况下将结果保存到数据库后立即获得?
ps:我需要的是如何在没有的情况下检索我的
specifications引用页面。
我应该将我的数据转换为 json 并通过 ajax 检索还是如何?
更新
我添加了新的函数和路由,以便在 ajax 中将我的数据作为 json 获取,这就是我现在拥有的:
controller
public function subspacs(){
$specifications = Specification::with('subspecifications')->get();
return response()->json($specifications);
}
route
Route::get('subspacs', 'ProductController@subspacs')->name('subspacs');
javascript
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"GET",
url:"{{ url('admin/subspacs') }}",
success : function(response) {
console.log(response);
}
});
});
</script>
问题
- 我的 Ajax 将在控制台
but not updated data中显示我的数据,问题 看到新数据需要刷新页面仍然存在。 -
为了
refresh my select box every 2 seconds,我尝试了下面的代码 通过 jQuery 并且有效。setTimeout ( function ( ) { $ ( ' #subspecifications ') . append ('< option value = "gg" >TEST SUCCESS< / option> '); } , 2000 ) ;
基本上我尝试了 2 种方法,但结果不成功:
- 使用 Ajax(未按预期工作)
- 尝试刷新我的选择框结果(成功)
现在question 是如何在选择框中将其父项下添加的规范?
屏幕截图
here is small video 看看现在到底发生了什么,避免误解。
【问题讨论】:
-
Ajax 绝对可以帮助您。创建一个操作以从数据库中检索数据。在 javascript 中使用 Ajax 调用它。
-
@anil_pulikoden 你介意帮我用 ajax 获取我的数据吗?我制作了
public function subspacs(){$specifications = Specification::all();return response()->json($specifications); }和路由Route::get('subspacs','ProductController@subspacs')->name('subspacs');我如何在刀片中显示它们? -
@anil_pulikoden 更新了我的问题
-
@devk 更新了我的问题