【发布时间】:2019-12-17 05:50:35
【问题描述】:
我在 Laravel 中有一个表单,用户可以在其中购买产品。我试图在不刷新页面的情况下动态实现这一点。我可以调用 AJAX 函数,但它没有将数据发布到控制器,我需要帮助。控制器中的所有内容都运行良好,只是没有发送数据。
这是 HTML 表单
<form class="buy-product-form" id="{{$product->id}}" action="/UoE/buy-product/{{$product->id}}" method="POST">
{{csrf_field()}}
<button class="pull-right btn btn-primary">BUY NOW</button>
</form>
这是我的 AJAX 函数
$(document).ready(function(){
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).closest("form").attr("id");
$.ajax({
url: $(this).closest("form").attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'JSON',
success: function () {
window.alert(url);
}
});
}));
});
这是控制器中的前几行
public function buyProduct($university_code, $product_id){
$player = Player::where('user_id', Auth::user()->id)->first();
$product = Product::where('id', $product_id)->first();
$totalPrice = $product->quantity_available * $product->price;
【问题讨论】:
-
您是否在控制台或调试栏中获得任何输出?
-
您是否在您的 ajax 文件中发送 csrf 令牌(例如在站点元数据中)?您表单中的 {{csrf_field()}} 不在您的控制器中的 ajax 帖子中,请参阅:laravel.com/docs/5.8/csrf#csrf-x-csrf-token
-
@jtwes 我现在也刚刚添加了元标记和 ajaxsetup 函数。不幸的是,这仍然行不通。
-
嗯。你至少应该看到一些东西或得到一个错误。添加 error: function(response) {console.log(response) } 并成功将响应输出到控制台。
-
我昨天确实收到了 Laravel 验证 CSRF 令牌错误,但我不记得是什么原因造成的,因为我的 ajax 函数甚至没有 URL 或任何内容。
标签: php jquery html ajax laravel