dongpankao6133 2016-03-14 13:10
浏览 108
已采纳

laravel 5.2 jQuery / AJAX从数据库加载内容

No idea if i've done this efficiently:

I am trying to load notifications from the database relevant to the Auth::user()->id in the notification table, and display them if they are unread (unread = 0)

I have a script in my app.blade.php: (it collects the array succesfully, but for the var request i want the '1' to be the variale 'id' but i don't know how to grab it correctly, also how do i display the contents of an array via javascript (foreach loop) confused with that (NOTE: i'm happy to swap to AJAX i don't know what would be better for this.

App.blade script

<script>
    $(document).ready(function() {
        $('.dropdown-toggle').on('click', function() {
            $('.menu').html('Loading please wait ...');
            var id = {{ Auth::user()->id }};

            var request = $.get('/notifications/1');
            request.done(function(response) {
              console.log(response);
              $(".menu").html(response);
            });
        });
    });

routes.php

route::get('/notifications/{user_id}', 'NotificationController@get');

NotificationController

public function get($user_id)
{
  $user = User::findOrFail($user_id);
  $notifications = Notification::all();
  // dd($notifications);
  $notification_array = $user->notifications()->where('read', 0)->get();

  return $notification_array;
}
  • 写回答

1条回答 默认 最新

  • duancan1950 2016-03-14 13:16
    关注

    Try this:

    var id = "{{ Auth::user()->id }}";
    var request = $.get('/notifications/' + id);
    

    Note the quotes around the assignment to id.

    Then to loop an array use:

    for (var index in myArray) {
        var e = myArray[index];
        // do something with e
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?