【发布时间】:2016-04-25 10:38:02
【问题描述】:
我有一个 ajax 调用正在向我的一个控制器发送一些 ID。
执行此操作的 jQuery 基本上是搜索 ID 为 notification-id- 的元素,然后获取 ID 并将它们存储在 JavaScript 变量中。
当我alert() 或console.log() 这个变量时,它会为我在页面notification-id-1 和notification-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->input()...notifications的值是多少?在浏览器控制台网络选项卡中,请求中发送的请求参数是什么?当您使用 returnResponse::json($output)而不是dd($output)时,您会得到不同的结果吗? -
我认为您没有正确发送数据
-
@WayneWhitty 当我在 Chrome 开发工具中记录请求时,在网络选项卡下,我单击请求并单击底部的表单数据,它为每个字段显示
undefined;。看起来 Ajax 请求没有正确发送数据......我将发布我正在使用的完整脚本,看看是否有助于调试。 -
你的问题出在客户端。通知是什么类型的JS变量?
标签: php ajax laravel laravel-5.1