【问题标题】:How to reload Laravel @includes with AJAX?如何使用 AJAX 重新加载 Laravel @includes?
【发布时间】:2019-06-07 16:43:03
【问题描述】:

我的较大应用程序中有一个单页应用程序,它会将数据发送到数据库,并且还会显示同一个表的数据。目前,我有 AJAX 动态发送数据。但是,要让刚刚插入的数据出现在我想要的表中,我必须刷新。我整个早上都在尝试,但下面是目前的状态。

观点:

<html>
  <head>
    <!--I took some stuff out to make it easier to look at -->
  </head>
  <body onresize="resizeRecalc()">
    <div class="container-fluid">
      <div class="row header">
        <div class="col-12">
          <img src="{{ URL::asset('images/takeStatsLogo.png') }}" id="header-logo" />
        </div>
      </div>
      <div class="mainArea row">
        <div class="left col-8">
          <div onclick="playPause()" class="embed-responsive embed-responsive-16by9">
            <video id="gameFilm" src="{{ URL::asset('images/basketball.mp4') }}" preload="metadata"></video>
          </div>

          <div class="timebar">
            <span class="timeItem" id="timestamp"></span>
            <div onclick="changeVidTime()" onmousemove="moveLine(event)" onmouseout="REmoveLine()" id="outerBox"> <div id="progressBox"> <div id="placeMarker">
                </div></div></div>
            <span class="timeItem" id="duration-place"></span>
          </div>

          <!-- This is a key part -->
          <div id="statList">
              @include('partials.statList')
          </div>
        </div>

        <div id="right" class="right col-4">
          <!--Checking if we should make the user select starters. If we have them, no need to do that...-->
          @if ($game->starters != null)
              @include('partials.areStarters')
          @else
              @include('partials.noStarters')
          @endif
        </div>
      </div>
    </div>
    <script>
      //Add Stat Form
      //This part here will add the stats, but it won't refresh them!
      $('input#addStatButton').click( function() {
          $.post( '{{action("StatController@store")}}', $('form#new_stat').serialize(), function(data) {
                $('#statList').load('/take-stats/{{$game->id}}');
             },
             'json' // I expect a JSON response
          );
          clearStat();
      });
    </script>
    <script src="{{ URL::asset('js/takeStats/genJavascript.js') }}"></script>
    <script src="{{ URL::asset('js/takeStats/videoJS.js') }}"></script>
    <script src="{{ URL::asset('js/takeStats/dataJS.js') }}"></script>
  </body>
</html>

这里是控制器方法:

public function loadStatList($id) {
    $userType = Auth::user()->user_type;
    if(Auth::check() && Game::where('id', '=', $id)->exists() && ($userType == 'statistician' || $userType == 'admin')) {
        $game = Game::find($id);
        $players = $game->team->users->where('user_type', 'player');
        $stats = Stat::orderBy('video_timestamp', 'desc')->where('game_id', $game->id)->get();
        $statMeta = Stat_Meta::all()->where('type', 'recorded');
        return view('partials.statList', compact('game', 'players', 'stats', 'statMeta'));
    } else {
        abort(404);
    }
}

我可能会遗漏一些东西,但我认为这会达到我想要达到的效果。

【问题讨论】:

  • 你不能那样做。您必须使用 ajax 响应数据使用 javascript 重建整个表,或者在 ajax 响应中返回已经呈现的 html。
  • 如何在部分中预渲染 html?这听起来比用 JS 重建表要好得多

标签: javascript jquery ajax laravel model-view-controller


【解决方案1】:

我想通了!感谢@Get Off My Lawn 给了我一点提示,我不能只使用@include。我继续研究如何预渲染 HTML,然后将其引入。实际上并不难。这里的想法是使用 JQuery 函数在点击提交时执行 AJAX POST,然后使用 .done 来获取新的完整网页。在你拥有之后(你可以 console.log 看看你当时正在使用什么,它将是整个网页)你可以从你执行的 .get 中获取你想要刷新的特定 div,然后坚持它在同一个div中。代码如下:

HTML/@include:

<div id="statList">
   @include('partials.statList')
</div>

AJAX/JQuery:

$('input#addStatButton').click( function() {
    $.ajax({
      type: 'POST',
      url: '{{action("StatController@store")}}',
      data: $('form#new_stat').serialize(),
    })
    .done(function(refresh) {
      clearStat();
      $.get('{{action("StatController@show", [$game->id])}}', function(data) {
        var newData = $("#statList" , data)
        $( "#statList" ).html( newData );
        //console.log(newData);
      });
    });
  });

你们太开心了!!!

【讨论】:

  • 你为什么不直接使用 $.load 或者在你的控制器中返回你需要的刀片。这有点乱
  • 用它代替 .done()?对不起,我真的对 JQuery 一无所知。我自己更像是一个香草人。
  • 我将提供一个关于如何使用 jquery 和 laravel 适当地返回数据或视图的答案。
【解决方案2】:

正如所讨论的,这不是您问题的答案,而是您在 cmets 中提出的简单解释。它可以帮助其他人

Laravel 和 JQuery

多么强大:-)

首先,我会尽量根据您提供的信息来满足您的需求。

其次,jquery 包含一些很多人不知道的很酷的功能。

正如您所描述的,您有一个单页网站或类似的网站。这意味着您有 1 个route 来显示我建议的单个页面/take-stats/{{$game-&gt;id}}。 在您的控制器中,我以GameController 为例,您有如下内容。

class GameController
{

 public function __construct()
 {

 }

 //the single page view
 public function index()
 {
     //your singlepage logic here....

     return view('games.index'); //something like this?
 }

 public function create() //this is where you post to
 {
    //logic to store the game stats...

    //this is where you return a succes message or something.
    //lets return the index instead :-)

    //dont't return $this->index! use redirect to the route.
    return redirect()->route('the.route.to.your.index');
 }


}

正如您在上面看到的,我们在发布响应中返回单个页面。 SSo 当您发布到 store 方法时,它成功返回索引页面。

现在是 jquery。

$('input#addStatButton').on( function() {
   //this is where to do the post.
    $.post(`{{ route('to.your.store.route') }}`, $('form#new_stat').serialize(), (response) => {

      //clear the stats because the post is succeeded in here
      //also reload the content. The response contains the new html content

      //now what we can do is replace the whole content....
      //something like $(`html`).html('response);
      //or we get the content we need from the response and this is where jquery comes in handy. The response is simply a html response so jquery can create a new dom from it.

      let statsList = $(response).find(`#statslist`).html(); //create a dom element of the response.
      $(`#statslist`).html(statslist); //put the filtered html in the current list.
      //thats all :-)
    }).fail(() => {
      // a fail save. When the post fails it will come in here.
    }).always(() => {
      clearStats(); 
      //this is called always even when it fails. You can clear the stats or something in here.
    });

});

简短说明:

  • 点击发帖按钮,发帖到post.route
  • 控制器方法执行逻辑并成功返回索引 url。
  • jquery 解析 html 响应并替换原始内容。
  • 完成。

我希望这对您或其他人有所帮助。当使用像上面这样的结构时,这段代码更简洁,更快,因为它只执行一个请求。

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多