从控制器中的ajax调用中检索数据

时间:2016-04-25 10:38:02

标签: php ajax laravel laravel-5.1

我有一个ajax调用,它正在向我的一个控制器发送一些ID。

正在运行的jQuery基本上是搜索具有notification-id-之类ID的元素,然后抓取ID并将它们存储在JavaScript变量中。

当我alert()console.log()此变量时,它会为1,2notification-id-1上的两个通知打印出notification-id-2等值。< / p>

对于我的ajax电话,我只是在做以下事情:

$.ajax({
  url: "{{ url('/notifications/read') }}",
  method: "POST",
  data: notifications, // Let jQuery handle packing the data for you
  success: function(response) {
       // The data was sent successfully and the server has responded (may have failed server side)
   alert(notifications);
  },
  error: function(xhr, textStatus, errorThrown) {
      // AJAX (sending data) failed
  },
  complete: function() {
      // Runs at the end (after success or error) and always runs
  }
});

我试图通过执行dd($request->all());来测试我的控制器正在接收的内容,但这只是返回:

array:1 [
  "undefined" => ""
]

(ajax调用确实成功运行)

如何检索控制器内此ajax调用中发送的ID值?

编辑:完整脚本

<script type="text/javascript">
  $(document).ready(function() {
    var count = $('#notification-counter');
    var new_notifications = $('#notification-new-counter');
    $('#notification-drop-down').on('click', function() {
      count.empty();
      var notifications = $('[id^="notification-id-"]').map(function() {
        return this.id.slice(16);
      }).get();
        $.ajax({
          url: "{{ url('/notifications/read') }}",
          method: "POST",
          data: notifications, // Let jQuery handle packing the data for you
          success: function(response) {
               // The data was sent successfully and the server has responded (may have failed server side)
               alert(notifications);
          },
          error: function(xhr, textStatus, errorThrown) {
              // AJAX (sending data) failed
          },
          complete: function() {
              // Runs at the end (after success or error) and always runs
          }
        });
    });
  });
</script>

2 个答案:

答案 0 :(得分:1)

$.ajax({
      url: "{{ url('/notifications/read') }}",
      method: "POST",
      data: {'notifications':notifications},

答案 1 :(得分:0)

请您使用以下代码并告诉我您在控制器中获得了什么? 数据:{notification:2} 。如果你正确地得到这个值,那么在你的原始帖子中你没有正确发送通知而没有在控制器中得到任何东西。