【问题标题】:How can you load a page fragment with jQuery in Laravel 4?如何在 Laravel 4 中使用 jQuery 加载页面片段?
【发布时间】:2013-06-22 20:36:48
【问题描述】:

我喜欢像这样使用 jQuery 加载页面片段:

$(".title" + nid ).click(function() {

   $('.loadNest').load("{{ View::make('postDetails') }}");

});

这可能吗?我的页面左侧有一个帖子标题列表。当用户单击帖子标题时,我想在右侧加载一个页面片段,其中包含帖子的所有详细信息。作者、cmets 等……都在同一页上。

【问题讨论】:

    标签: javascript php jquery laravel laravel-4


    【解决方案1】:

    jQuery 的load 方法实际上是一个AJAX 调用,因此您必须设置一个输出视图的路由。像这样的:

    Route::get('ajax/postDetails', array(
        'as' => 'postDetailsView', // This is the name of your route
        'do' => function () {
            return View::make('postDetails');
        }
    ));
    

    然后,在您的代码中,您将拥有:

    $('.title' + nid).click(function() { // Use the route's name you setup
        $('.loadNest').load('{{ URL::route('postDetailsView') }}');
    });
    

    【讨论】:

    • 无法让它工作。你能成功地测试它吗?
    • 我以前没有见过在这种情况下使用的'do'。像这样在这里使用它有特定的理由吗?
    • do 用于Closures uses 用于控制器方法。
    【解决方案2】:

    我通过使用这个 jQuery 代码解决了这个问题:

    $(".nestTitle").click(function(e){
        $.ajax({
          url: "getNest",
          context: document.body
        }).done(function(fragment) { 
          $(".loadNest").html(fragment);
        });
    });
    

    这样称呼我的路线:

    Route::get('getNest', array('as' => 'getNest', 'uses' => 'NestsController@getNest'));
    

    然后在我的控制器中我这样做了:

        $nid = 105;
        $uid = Auth::user()->id;
        $nests = Nest::with('user')
        ->where('user_id', '=', $uid)
        ->where("id", $nid)
        ->get();
    
        return View::make('nestItems', compact('nests'));
    

    我只需要传递参数,我应该很好。感谢您的帮助拉斐尔。

    【讨论】:

      【解决方案3】:

      我使用的一个干净的解决方案是在您的 javascript 中使用资产

      $(".title" + nid ).click(function() {
      
         $('.loadNest').load("{{ asset('postDetails') }}");
      
      });
      

      并将路线设置为

      Route::get('/postDetails', function() {
          return View::make('postDetails');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        相关资源
        最近更新 更多