search
HomePHP FrameworkLaravelSimple application tutorial of PHP+Laravel [Usage of ajax]

The following is a simple application tutorial of PHP Laravel [Usage of ajax] from the Laravel Frameworktutorial column. I hope it will be helpful to friends in need!

Statement

This article is just a scattered application tutorial. The default Laravel project has been installed and running normally;

Ajax Use

Create a controller

Run the command in the project root directory

php artisan make:controller TestController

If the creation is successful, you will be promptedController created successfully.
After successful creation, the TestController.php file will be generated in the app/Http/Controllers/ directory
Add to the TestController.php file

public function index(){
    return view('test');}public function testAjax(){
    echo '请求成功了';die;}

PHP + Laravel 的简单应用教程 — ajax 的使用

Create a view file

Create a new view file in the resources/views directory test.blade.php

PHP + Laravel 的简单应用教程 — ajax 的使用
The contents of the file are as follows

PHP + Laravel 的简单应用教程 — ajax 的使用

Routing configuration

Open the routing fileroutes/web.php, the default route is as follows:

PHP + Laravel 的简单应用教程 — ajax 的使用

Add a route below to display the test Ajax page

Route::get('test', [TestController::class, 'index'])->name('test.index');

Add a new route to receive Ajax requests

Route::post('test', [TestController::class, 'testAjax'])->name('test.ajax');

For more routing related information, please check the document routing "Laravel 8 Chinese Documentation" (Address: https://learnku.com/docs /laravel/8.x/routing/9365)

Add the entrance to the test page

Openresources/views/welcome.blade. php file, find about line 111:

PHP + Laravel 的简单应用教程 — ajax 的使用

Copy the content and modify it to the required test page entrance

<a>
    测试入口</a>

PHP + Laravel 的简单应用教程 — ajax 的使用

After saving, refresh the page and you will see the test entrance

PHP + Laravel 的简单应用教程 — ajax 的使用

Click on the test entrance to enter the test page and you will see the following content

PHP + Laravel 的简单应用教程 — ajax 的使用

Modify the page content

Put the downloaded jquery.min.js into public/assets/ Directory

PHP + Laravel 的简单应用教程 — ajax 的使用

Modify the contents of the resources/views/test.blade.php file

nbsp;html>
    <meta>
    <title>Test Ajax</title>
    <script></script>
    返回的内容:<p></p>
    
        {!! csrf_field() !!}         提交的内容:         提交     
<script> $(&#39;.submit-btn&#39;).click(function () { let url = $(this).closest(&#39;form&#39;).attr(&#39;action&#39;); let formData = $(this).closest(&#39;form&#39;).serialize(); $.post(url,formData,function (response) { $(&#39;.response-message&#39;).text(response); }) })</script>

Click on the ## of the test page #Submit You can see that the content returned by testAjax() in the controller has been displayed on the page

PHP + Laravel 的简单应用教程 — ajax 的使用

PHP + Laravel 的简单应用教程 — ajax 的使用

File path

app/Http/Controllers/TestController.php Original content

PHP + Laravel 的简单应用教程 — ajax 的使用Modified content:

PHP + Laravel 的简单应用教程 — ajax 的使用

修改前端页面

文件路径 resources/views/test.blade.php

$('.submit-btn').click(function () {
        let url = $(this).closest('form').attr('action');
        let formData = $(this).closest('form').serialize();
        $.post(url,formData,function (response) {
            let responseData = response.data;
            let appendStr = '<span>'+responseData.text+'</span>';
            $('.response-message').empty().append(appendStr);
        })})

保存后在页面输入框中输入内容,点击提交后即可看到最新内容

PHP + Laravel 的简单应用教程 — ajax 的使用

结语

本文讲的是基础的接口应用,还有比如 Vue、Recat、mui 等项目中请求接口的示例请自行了解                                             

The above is the detailed content of Simple application tutorial of PHP+Laravel [Usage of ajax]. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment