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

半城伤御伤魂 提交于 2021-02-07 12:58:18

问题


As the title says, I am trying to dynamically load content in a view using ajax requests. I know this can be done if you are using html elements e.g. ("#div_place").html(<p>...). The problem lies when I would like to load some php/blade objects into a div for instance. Is this possible or is there a different way to go about achieving the result I want.


回答1:


This is pretty straightforward. Assuming you're using jQuery...

  1. create a route that will respond to the AJAX call and return an HTML fragment

    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. in your javascript:

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



回答2:


After some digging some more I found this which helped me to solve the problem.

You have to use the .load("url/page/...") via jquery and then set a route in the routes.php file that displays a view with the data that needs to be loaded e.g.

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

This returns the necessary php code which needed to be loaded dynamically, cheers.



来源:https://stackoverflow.com/questions/24812785/how-to-load-blade-or-php-content-into-a-view-via-ajax-jquery-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!