【问题标题】:Retrieving data from ajax call in controller从控制器中的ajax调用中检索数据
【发布时间】:2016-04-25 10:38:02
【问题描述】:

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

执行此操作的 jQuery 基本上是搜索 ID 为 notification-id- 的元素,然后获取 ID 并将它们存储在 JavaScript 变量中。

当我alert()console.log() 这个变量时,它会为我在页面notification-id-1notification-id-2 上的两个通知打印出1,2 之类的值。

对于我的 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>

【问题讨论】:

  • 您是否使用浏览器(Chrome 开发者工具等)检查了 Ajax 请求?帖子字段是否存在且正确?
  • 我为此使用$request-&gt;input()...notifications 的值是多少?在浏览器控制台网络选项卡中,请求中发送的请求参数是什么?当您使用 return Response::json($output) 而不是 dd($output) 时,您会得到不同的结果吗?
  • 我认为您没有正确发送数据
  • @WayneWhitty 当我在 Chrome 开发工具中记录请求时,在网络选项卡下,我单击请求并单击底部的表单数据,它为每个字段显示 undefined;。看起来 Ajax 请求没有正确发送数据......我将发布我正在使用的完整脚本,看看是否有助于调试。
  • 你的问题出在客户端。通知是什么类型的JS变量?

标签: php ajax laravel laravel-5.1


【解决方案1】:
$.ajax({
      url: "{{ url('/notifications/read') }}",
      method: "POST",
      data: {'notifications':notifications},

【讨论】:

  • 这就像一个魅力。谢谢苏尼尔!它现在显示一个通知变量,其中包含正在发送的值 - 这正是我所追求的!
【解决方案2】:

您能否使用以下行告诉我您在控制器中得到了什么? 数据:{notifications:2}。如果您正确获取了此值,那么在您的原始帖子中,您没有正确发送通知并且在控制器中没有得到任何东西。

【讨论】:

  • 这会在响应中显示“通知”:“2”。我发现我没有正确发送它们,但我不确定如何正确发送它们。
  • 能否请您使用 console.log(notifications) 打印价值并给我价值。
猜你喜欢
  • 1970-01-01
  • 2019-12-16
  • 2017-06-23
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
相关资源
最近更新 更多