我有一個 laravel 刀片視圖/頁面,我想在不重繪 頁面的情況下進行更新。
blade.php 代碼作業正常并從 MySQL 資料庫檢索資料 - 但 ajax/javascript 不是。
顯然我的 AJAX 呼叫甚至沒有回傳 JSON,而是一個物件。
我來自 C# 背景,在我的生活中從未接觸過 ajax/javascript/php,如果有人能幫助我,我將不勝感激。
controller.php 作業并回傳我需要的資料,這些資料看起來像 json 但顯然不是 json。
我想做的是重繪 用戶所在的頁面(無需重新加載),從 MySQL 資料庫中獲取資料并使用此新資料更新預先存在的表 - 如果有任何新資料。
查看.blade.php:
<table class="table custom--table" id="mainTable">
<thead>
<tr>
<th>@lang('ID')</th>
<th>@lang('Name')</th>
<th>@lang('Date')</th>
<th>@lang('Details')</th>
</tr>
</thead>
<tbody>
@forelse($items as $data)
<tr>
<td data-label="@lang('ID')">
{{ $loop->index 1 }}
</td>
<td data-label="@lang('Name')">{{ $data->name }}</td>
<td data-label="@lang('Date')">{{ $data->created_at }}</td>
<td id="detailz" data-label="@lang('Details')">{{ $data->details }}</td>
</tr>
@empty
<tr>
<td colspan="100%" class="text-center justify-content-center">@lang('No data.')</td>
</tr>
@endforelse
</tbody>
</table>
AJAX:(不作業)
function updatePost() {
setInterval(function() {
$.ajax({
type: "GET",
url: "{{route('user.posts.update')}}", // Route works.
success: function( response ){
$('#mainTable')[0].reset();
$("tbody").html("");
$.each(response, function( index, value ) {
var row = $("<tr><td>"
value.name "</td><td>"
value.details "</td><td>"
value.created_at "</td><td>");
$("tbody").append(row);
});
},
error: function( response ){
console.log("Error!");
console.log(response);
}
});
}, 5000); // every 5s
控制器.php:
public function postUpdate(){
$pageTitle = 'Post Update';
$data = DataHistory::where('user_id', Auth::user()->id)->latest()->paginate(getPaginate());
return response()->json($data);
}
我在 ajax 中嘗試了許多不同的方法,但顯然我似乎無法訪問資料的內部元素。
這是資料示例:
{
"current_page":1,
"data":[
{
"id":34,
"user_id":1,
"name":"RANDOM NAME DATA",
"details":"RANDOM DETAILS",
"created_at":"2022-11-16T15:02:56.000000Z"
},{
"id":32,
"user_id":1,
"name":"RANDOM NAME DATA 2",
"details":"RANDOM DETAILS 2",
"created_at":"2022-11-16T10:19:29.000000Z"
},
"first_page_url":"https:\/\/xyz.com/posts/update/?page=1",
"from":1,
"last_page":1,
"last_page_url":"https:\/\/xyz.com/posts/update/?page=1",
"links":[
{
"url":null,
"label":"« Previous",
"active":false
},{
"url":"https:\/\/xyz.com/posts/update/?page=1",
"label":"1",
"active":true
},{
"url":null,
"label":"Next »",
"active":false
}
],
"next_page_url":null,
"path":"https:\/\/xyz.com/posts/update/",
"per_page":20,
"prev_page_url":null,
"to":7,
"total":7
}
我將如何實作這一目標?我正朝著正確的方向前進嗎?
uj5u.com熱心網友回復:
你所擁有的是有效的 JSON,但它是一個物件而不是陣列。在data屬性中有一個陣列。所以如果你回圈response.data它會作業:
$.each(response.data, function( index, value ) {
uj5u.com熱心網友回復:
您可能想要迭代回應屬性data
$.each(response.data, function( index, value ) {
這樣value.name實際上將包含演示資料中這些物件的值:
{
"id":34,
"user_id":1,
"name":"RANDOM NAME DATA",
"details":"RANDOM DETAILS",
"created_at":"2022-11-16T15:02:56.000000Z"
},{
"id":32,
"user_id":1,
"name":"RANDOM NAME DATA 2",
"details":"RANDOM DETAILS 2",
"created_at":"2022-11-16T10:19:29.000000Z"
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/535340.html
