Home Web Front-end JS Tutorial Detailed explanation of pjax use cases in laravel framework

Detailed explanation of pjax use cases in laravel framework

May 24, 2018 am 11:55 AM
laravel pjax Case

This time I will bring you a detailed explanation of the use cases of pjax in the laravel framework. What are the precautions for using pjax in the laravel framework. The following is a practical case, let's take a look.

Regarding what pjax is, readers are asked to Baidu.

Preparation:
1. Download the jquery.pjax.js file and click download
2. Download NProgress
3. Put the required files into the project. and referenced in the layout file. (Under the framework public directory)

Start:
Here I am using the adminLTE backend template. For specific usage, please refer to Using AdminLTE in Laravel5.*

Installing pjaxcomposer Package (laravel middleware):

$ composer require spatie/laravel-pjax
Copy after login

Add code to the kernel.php file:

// app/Http/Kernel.php
...
protected $middleware = [
...
\Spatie\Pjax\Middleware\FilterIfPjax::class,
];
Copy after login

Configure pjax to complete page interaction: (ps: The author uses pjax to load pages throughout the site, Therefore, pjax is configured in the global js file, and readers can configure it separately as needed)

$.pjax.defaults.timeout = 5000;
$.pjax.defaults.maxCacheLength = 0;
//配置可点击的<a>标签使用pjax
$(document).pjax('a:not(a[target="_blank"])', {
    container: '#pjax-container'//配置pjax刷新容器
});
NProgress.configure({parent: '#pjax-container'});
//超时执行函数
$(document).on('pjax:timeout', function (event) {
    event.preventDefault();
});
Copy after login

At this point, laravel combined with pjax has been completed.

Attachment:
The author’s layout (layout.blade.php):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>AdminLTE</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/bower_components/bootstrap/dist/css/bootstrap.min.css&#39;)}}">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/bower_components/font-awesome/css/font-awesome.min.css&#39;) }}">
    <!-- Ionicons -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/bower_components/Ionicons/css/ionicons.min.css&#39;) }}">
    <!-- select2 -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/bower_components/select2/dist/css/select2.min.css&#39;) }}">
    <!-- DataTables -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css&#39;) }}">
    <link rel="stylesheet" href="{{ asset(&#39;js_expand/dataTables.buttons/buttons.dataTables.min.css&#39;) }}">
    <!-- Theme style -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/dist/css/AdminLTE.min.css&#39;) }}">
    <!-- AdminLTE Skins -->
    <link rel="stylesheet" href="{{ asset(&#39;AdminLTE/dist/css/skins/skin-blue.min.css&#39;) }}">
    <!-- nprogress -->
    <link rel="stylesheet" href="{{ asset(&#39;js_expand/nprogress/nprogress.css&#39;) }}">
    <!-- toastr -->
    <link rel="stylesheet" href="{{ asset(&#39;js_expand/toastr/build/toastr.min.css&#39;) }}">
    <!-- sweetalert -->
    <link rel="stylesheet" href="{{ asset(&#39;js_expand/sweetalert/dist/sweetalert.css&#39;) }}">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn&#39;t work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <!-- Google Font -->
    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
    <!-- REQUIRED JS SCRIPTS -->
    <!-- jQuery 3 -->
    <script src="{{ asset(&#39;AdminLTE/bower_components/jquery/dist/jquery.min.js&#39;) }}"></script>
    <!-- jQuery 2 -->
    <script src="{{ asset(&#39;js_expand/jQuery/jQuery-2.1.4.min.js&#39;) }}"></script>
    <!-- Bootstrap 3.3.7 -->
    <script src="{{ asset(&#39;AdminLTE/bower_components/bootstrap/dist/js/bootstrap.min.js&#39;) }}"></script>
    <!-- Select2 -->
    <script src="{{ asset(&#39;AdminLTE/bower_components/select2/dist/js/select2.full.min.js&#39;) }}"></script>
    <!-- AdminLTE App -->
    <script src="{{ asset(&#39;AdminLTE/dist/js/adminlte.min.js&#39;) }}"></script>
    <!-- dataTables -->
    <script src="{{ asset(&#39;AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js&#39;) }}"></script>
    <script src="{{ asset(&#39;AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js&#39;) }}"></script>
    <script src="{{ asset(&#39;js_expand/dataTables.lan.js&#39;) }}"></script>
    <script src="{{ asset(&#39;js_expand/dataTables.buttons/dataTables.buttons.min.js&#39;) }}"></script>
    <script src="{{ asset(&#39;vendor/datatables/buttons.server-side.js&#39;) }}"></script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<p class="wrapper">
    <!-- Main Header -->
    @include('admin::partials.header')
    <!-- Left side column. contains the logo and sidebar -->
    @include('admin::partials.sidebar')
    <!-- Content Wrapper. Contains page content -->
    <p class="content-wrapper">
        <!-- Main content -->
        <section class="content container-fluid" id="pjax-container">
            @yield('content') 
            
        </section>
        <!-- /.content -->
    </p>
    <!-- /.content-wrapper -->
    <!-- Control Sidebar -->
    @include('admin::partials.control')
    <!-- /.control-sidebar -->
    <!-- Main Footer -->
    @include('admin::partials.footer')
</p>
<!-- ./wrapper -->
<script>
    var csrf_token = '{{ csrf_token() }}';
</script>
<!-- nprogress -->
<script src="{{ asset(&#39;js_expand/nprogress/nprogress.js&#39;) }}"></script>
<!-- pjax -->
<script src="{{ asset(&#39;js_expand/jquery-pjax/jquery.pjax.js&#39;) }}"></script>
<!-- toastr -->
<script src="{{ asset(&#39;js_expand/toastr/build/toastr.min.js&#39;) }}"></script>
<!-- sweetalert -->
<script src="{{ asset(&#39;js_expand/sweetalert/dist/sweetalert.min.js&#39;) }}"></script>
<!-- admin.base -->
<script src="{{ asset(&#39;js_expand/laravel-admin/admin.base.js&#39;) }}"></script>
<!-- custom script-->
<script>
    var selectedMenu = "{!! $requestUri !!}";
</script>
</body>
</html>
Copy after login

Global js file (admin-base.js):

toastr.options = {
    closeButton: true,
    progressBar: true,
    showMethod: 'slideDown',
    positionClass: 'toast-top-right',
    timeOut: 4000
};
$.pjax.defaults.timeout = 5000;
$.pjax.defaults.maxCacheLength = 0;
$(document).pjax('a:not(a[target="_blank"])', {
    container: '#pjax-container'
});
NProgress.configure({parent: '#pjax-container'});
$(document).on('pjax:timeout', function (event) {
    event.preventDefault();
});
$(document).on('submit', 'form[pjax-container]', function (event) {
    $.pjax.submit(event, '#pjax-container')
});
$(document).on("pjax:popstate", function () {
    $(document).one("pjax:end", function (event) {
        $(event.target).find("script[data-exec-on-popstate]").each(function () {
            $.globalEval(this.text || this.textContent || this.innerHTML || '');
        });
    });
});
$(document).on('pjax:send', function (xhr) {
    if (xhr.relatedTarget && xhr.relatedTarget.tagName && xhr.relatedTarget.tagName.toLowerCase() === 'form') {
        $submit_btn = $('form[pjax-container] :submit');
        if ($submit_btn) {
            $submit_btn.button('loading')
        }
    }
    NProgress.start();
});
$(document).on('pjax:complete', function (xhr) {
    if (xhr.relatedTarget && xhr.relatedTarget.tagName && xhr.relatedTarget.tagName.toLowerCase() === 'form') {
        $submit_btn = $('form[pjax-container] :submit');
        if ($submit_btn) {
            $submit_btn.button('reset')
        }
    }
    NProgress.done();
});
$(function () {
    $('.sidebar-menu li:not(.treeview) > a').on('click', function () {
        var $parent = $(this).parent().addClass('active');
        $parent.siblings('.treeview.active').find('> a').trigger('click');
        $parent.siblings().removeClass('active').find('li').removeClass('active');
    });
    $('[data-toggle="popover"]').popover();
    //整页刷新时,菜单显示
    var selector = $('.sidebar-menu').find('a[href="/'+ selectedMenu +'"]');
    selector.parent().addClass('active');
    selector.parents('ul.treeview-menu').css('display', 'block');
    selector.parents('li.treeview').addClass('menu-open');
    //datatables删除按钮
    $('#pjax-container').on('click', '.row-delete', function () {
        var del_url = $(this).data('url');
        swal({
            title: "确定删除此项?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确 定",
            closeOnConfirm: false,
            cancelButtonText: "取 消"
        }, function(){
            $.ajax({
                method: 'post',
                url: del_url,
                data: {
                    _method:'delete',
                    _token:csrf_token,
                },
                success: function (data) {
                    if (typeof data === 'object') {
                        if (data.status) {
                            swal(data.message, '', 'success');
                            $.pjax.reload('#pjax-container');
                        } else {
                            swal(data.message, '', 'error');
                        }
                    }
                }
            });
        });
    });
});
Copy after login

I believe I have read it You have mastered the method in the case of this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for combining React with TypeScript and Mobx

Detailed explanation of the steps for using React-router v4

The above is the detailed content of Detailed explanation of pjax use cases in laravel framework. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles