Laravel:渲染与AJAX请求局部视图视图、局部、Laravel、AJAX

2023-09-10 17:48:30 作者:掌握全局

我想做一个单页的CRUD应用程序,我使用AJAX使用jQuery。在这种情况下,我提交的形式和新的国家在我的数据库存储异步然后渲染新数据的局部视图。

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]);
    }

    // ...

}

不过,我不喜欢实际上呈现在页面视图使用jQuery的想法,感觉这应该是Laravel的工作。

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.

我怎么能渲染Laravel的局部视图以及使用Ajax,而不必委派工作的jQuery(追加()空())?

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())?

推荐答案

您也越来越糊涂了。

Laravel的已经是的做局部的渲染。您调用查看::使()并返回渲染的以 $ HTML

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

然后您传递渲染视图jQuery的,这简直是显示给它的数据 - 它没有做任何的计算本身

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.