PHP Laravel Ajax 函数未在 Blade 模板中调用

问题描述 投票:0回答:1

我目前正在尝试创建一个 Blade 页面,其中显示 3 个框,在其下方是从后端检索的通知列表。为了加载通知列表,我尝试对 API 端点进行 ajax 调用。

我的主页刀片:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" 
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
    crossorigin="anonymous">
</head>
<body>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Total revenue (30 days)</h5>
        <p class="card-text">{{ $totalRevenue }}</p>
      </div>
    </div>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Total followers (30 days)</h5>
        <p class="card-text">{{ $totalFollowers }}</p>
      </div>
    </div>
    <div class="card" style="width: 18rem;">
      <div class="card-body">
        <h5 class="card-title">Top 3 item sales (30 days)</h5>
        @foreach($topItemSales as $topItemSale)
          <p class="card-text"> 
            {{ $topItemSale->item_name }}
          </p>
          <p class="card-text"> 
            {{ $topItemSale->total }}
          </p>
        @endforeach
      </div>
    </div>
    <div id="item-lists">
        @include('layouts.notificationlist')
    </div>
    <script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" 
    integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" 
    crossorigin="anonymous"></script>

    <script type="text/javascript">
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            }else{
                getData(page);
            }
        }
    });

    $(document).ready(function()
    {
        $(document).on('click', '.pagination a',function(event)
        {
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
            event.preventDefault();
        
            var myurl = $(this).attr('href');
            var page=$(this).attr('href').split('page=')[1];
            
            getData(page);
        });
    });

    function getData(page){
        $.ajax({
            url: '?page=' + page,
            type: "get",
            datatype: "html",
        })
        .done(function(data){
            $("#item-lists").empty().html(data);
            location.hash = page;
        })
        .fail(function(jqXHR, ajaxOptions, thrownError){
              alert('No response from server');
        });
    }

    </script>
</body>
</html>

我的通知列表刀片(我想要显示的通知列表)

<table class="table table-bordered">
<tbody>
    @foreach($notifications as $notification)
        <li class="list-group-item">{{ $notification['msg'] }}</li>
          <input type="checkbox" class={{ $notification['identifier'] }} name={{ $notification['id'] }} value={{ $notification['is_read'] }}">
        <br></br>
    @endforeach
</tbody>
</table>


{!! $notifications->render() !!}

我的路线/web.php:

<?php

use App\Http\Controllers\LoginController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\NotificationController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::group( ['middleware' => 'auth' ], function()
{
    Route::get('/home', [UserController::class, 'index'])->name("index");
    Route::post('/update', [UserController::class, 'update'])->name("update");
    Route::get('/home/page', [NotificationController::class, 'index'])->name('index');
});

Route::get('login', [LoginController::class, 'index'])->name('login');
Route::get('login/{provider}', [LoginController::class, 'redirectToProvider']);
Route::get('{provider}/callback', [LoginController::class, 'handleProviderCallback']);

我的用户控制器:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Services\FollowerService;
use App\Services\MerchSaleService;
use App\Services\RevenueService;
use App\Services\NotificationService;
use Auth;

class UserController extends Controller
{
    public function __construct(
        protected FollowerService $followerService,
        protected MerchSaleService $merchSaleService,
        protected RevenueService $revenueService,
        protected NotificationService $notificationService
    ) {
        $this->followerService = $followerService;
        $this->merchSaleService = $merchSaleService;
        $this->revenueService = $revenueService;
        $this->notificationService = $notificationService;
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $totalFollowers = $this->followerService->getTotalFollowers(30, Auth::id());
        $topItemSales = $this->merchSaleService->getTopItems(30, 3, Auth::id());
        $totalRevenue = $this->revenueService->getTotalRevenue(30, Auth::id());
        return view('layouts/home')
            ->with('totalFollowers', $totalFollowers)
            ->with('topItemSales', $topItemSales)
            ->with('totalRevenue', $totalRevenue);
    }
}

我的通知控制器:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Services\FollowerService;
use App\Services\MerchSaleService;
use App\Services\RevenueService;
use App\Services\NotificationService;
use Auth;

class NotificationController extends Controller
{
    public function __construct(
        protected FollowerService $followerService,
        protected MerchSaleService $merchSaleService,
        protected RevenueService $revenueService,
        protected NotificationService $notificationService
    ) {
        $this->followerService = $followerService;
        $this->merchSaleService = $merchSaleService;
        $this->revenueService = $revenueService;
        $this->notificationService = $notificationService;
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $notifications = $this->notificationService->getNotifications(100, Auth::id(), null);
        $notificationStrings = [];
        foreach ($notifications as $notification) {
            if ($notification->identifier == 'merch_sale') {
                array_push($notificationStrings, [
                    'id' => $notification->id,
                    'identifier' => $notification->identifier,
                    'is_read' => $notification->is_read,
                    'msg' => $notification->buyer.' bought '.$notification->amount.$notification->item_name.' from you for '.$notification->price.' '.$notification->currency.' at '.$notification->created_at
                ]);
            }
            elseif ($notification->identifier == 'follower') {
                array_push($notificationStrings, [
                    'id' => $notification->id,
                    'identifier' => $notification->identifier,
                    'is_read' => $notification->is_read,
                    'msg' => $notification->name.' followed you at '.$notification->created_at
            ]);
            }
            elseif ($notification->identifier == 'subscriber') {
                array_push($notificationStrings, [
                    'id' => $notification->id,
                    'identifier' => $notification->identifier,
                    'is_read' => $notification->is_read,
                    'msg' => $notification->name.' (Tier '.$notification->subscription_tier.') subscribed to you at '.$notification->created_at
                ]);
            } 
            elseif ($notification->identifier == 'donation') {
                array_push($notificationStrings, [
                    'id' => $notification->id,
                    'identifier' => $notification->identifier,
                    'is_read' => $notification->is_read,
                    'msg' => $notification->donator.' donated '.$notification->amount.' '.$notification->currency.' to you at '.$notification->created_at
                ]);
            }
        }
        if ($request->ajax()) {
            return view('notificationlist', $notificationStrings);
        }
        return view('notifications', $notificationStrings);
    }
}

但是,当我加载页面时,它说 $notifications 变量在 notificationlist 刀片中未定义。

为什么会这样呢?我认为在我的 Ajax 中,文档准备好后,它应该向 /home/page 端点发送请求,该端点应该返回 $notification 数据?

我也尝试过在 Blade 模板中插入 console.log 语句,但它们都没有在任何 JS 函数中打印。

谢谢!

php ajax laravel
1个回答
0
投票

你混淆了一些不同的范式。

如果您想混合使用 javascript 和 Blade,我的建议是使用令人惊叹的 livewire,它非常棒,并且可以让您按照您的建议进行操作。

就目前情况来看,您尝试做的事情是行不通的,您将服务器端代码(刀片)与客户端代码(javascript)混合在一起,实际上两者永远不会相遇。当你的 JavaScript 运行时,它并不是在查看刀片页面(即使是它也不知道如何处理它),而是在查看一个普通的 html 页面。

如果您希望在 javascript 中从服务器中收回数据并使用它在页面上渲染,您将需要编写 javascript 渲染代码或使用 javascript 模板引擎,但我建议您看看 livewire。

© www.soinside.com 2019 - 2024. All rights reserved.