Laravel: rendering partial views with AJAX requests

我是研究僧i 提交于 2019-12-09 10:51:20

问题


I am trying to make a single page CRUD application and I am using AJAX with jQuery. In this case, I submit the form and store a new country in my database asynchronously and then render a partial view with the new data.

This is my script and the method that retrieves the countries from the database and returns the partial view.

$('#create-country-form').submit(function(event) {
    $.post('/country/store', $('#create-country-form').serialize(), function() {
        $.get('/country/all', function(data) {
            $('#countries-table').empty();
            $('#countries-table').append(data['html']);
        });
    });
    event.preventDefault();
});

class CountryController extends BaseController {

    public function all() {
        $countries = Country::All();

        $html = View::make('countries.list', compact('countries'))->render();

        return Response::json(['html' => $html]);
    }

    // ...

}

However, I don't like the idea of actually rendering the view in the page using jQuery, it feels like this should be Laravel's work.

How can I render with Laravel a partial view along with the use of AJAX, and not having to delegate that work to jQuery (append() and empty())?


回答1:


You are getting confused.

Laravel is already doing the rendering of the partial. You are calling View::make() and returning the rendered view to $html.

Then you are passing the rendered view to jQuery, which is simply displaying the data given to it - its not doing any of the calculations itself.




回答2:


Pass your view to view helper, render it into a variable and return that variable as response to AjAx.

$view=view('your-view-blade');
$view=$view->render();
$responseData->responseSuccess($view);

In callback of your AjAx you can use that rendered HTML, you are free to append that HTML to any element.




回答3:


Use string method before view file

return (String) view('Company.allUserAjax');


来源:https://stackoverflow.com/questions/24984073/laravel-rendering-partial-views-with-ajax-requests

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