如何在laravel中通过ajax/jquery加载刀片或php内容到视图中

How to load blade or php content into a view via ajax/jquery in laravel?

本文关键字:php 加载 视图 jquery laravel ajax      更新时间:2023-09-26

正如标题所说,我正在尝试使用ajax请求动态加载视图中的内容。我知道这是可以做到的,如果你使用html元素,例如("#div_place").html(<p>...)。问题在于当我想加载一些php/刀片对象到一个div实例。这是可能的吗?还是有不同的方法去实现我想要的结果?

这很简单。假设您正在使用jQuery…

  1. 创建一个路由来响应AJAX调用并返回一个HTML片段

    Route::get('test', function(){
        // this returns the contents of the rendered template to the client as a string
        return View::make("mytemplate")
            ->with("value", "something")
            ->render();
    });
    
  2. :

    $.get(
        "test",
        function (data) {
            $("#my-content-div").html(data);
        }
    );
    

经过一番挖掘,我发现这有助于我解决问题。

你必须通过jquery使用.load("url/page/..."),然后在routes.php文件中设置一个路由,显示一个需要加载数据的视图,例如

Route::get('/url/page/...', function(){
    return View::make('test');
});

这将返回需要动态加载的必要php代码,干杯。