【问题标题】:Loading a blade template from AJAX从 AJAX 加载刀片模板
【发布时间】:2020-08-07 02:23:49
【问题描述】:

我有一个 AJAX 调用,我希望它返回带有查询结果的刀片模板。

我的 jQuery 代码:

$(document).on('click','.user-profile-child', function(){

    let id = $(this).parents('.user-profile-parent').attr('id');

    $.ajax({

        url: '/loadUserProfile',
        type: 'GET',
        data: {id: id},
        dataType: 'json',
        success: function(r){

            console.log(r);

        }

    })

});

我的函数必须执行查询并返回带有结果的视图:

public function loadUserProfile(Request $request){

        $id = $request->input('id');

        $user = User::where('id',$id)->get()->toArray();

        $returnHTML = view('userProfile')->with('user', $user)->render();
        return response()->json(array('success' => true, 'html'=>$returnHTML));

    }

这是我在控制台https://ibb.co/dth85Kh得到的

我尝试过这样编写我的函数,但它不会重定向到我的视图,也不会成功返回任何内容。

public function loadUserProfile(Request $request){

        $id = $request->input('id');

        $user = User::where('id',$id)->get()->toArray();

        return view('userProfile',['user' => $user]);

    }

【问题讨论】:

  • 您是否检查了调试器或控制台以查看是否有任何错误。至少在您的第一个示例中,您将返回 JSON。它实际上返回了什么,因为它在内容中说“这是一个测试”。
  • 它返回我的userProfile刀片模板的HTML标记。但我不知道如何加载它。
  • 如果你在你的 AJAX 调用中得到它,你应该能够 console.log(r.html) 或 $("#containerid").html(r.html); ?我不太了解 Laravel,但您可能必须为您的案例渲染没有页眉和页脚的视图,因此您可能只需要渲染您想要的内容。
  • 这里有一个如何只渲染一个部分的例子:stackoverflow.com/questions/15096241/…

标签: jquery ajax laravel


【解决方案1】:

这是不可能的。

Blade 视图助手编译为 php 代码。在将页面发送到浏览器之前,php 是在服务器端读取的,因此您无法动态运行 php 代码。所以没有。

我建议使用 InnerHtml 它使用 JavaScript 和 HTML 将您的数据附加到视图中。

【讨论】:

    猜你喜欢
    • 2020-08-22
    • 2018-08-11
    • 2018-06-26
    • 2014-02-02
    • 2016-10-02
    • 2019-04-03
    • 2014-03-01
    • 1970-01-01
    • 2016-10-23
    相关资源
    最近更新 更多