0
我開發了一個簡單的Ajax code.According這個圖像時,點擊+數量增加,當點擊 - 數量減少 Laravel 5.2 AJAX代碼不起作用
代碼在網上_help.blade.php
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function(){
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var increment = $(this).data('increase');
var itemId = $('.cart_quantity_input').val();
$.ajax({
type:'post',
url:'getmsg',
dataType:'json',
data:{
'item_id': itemId,
'increase': increment
},
success:function(data){
$("cart_quantity_input").val(data.qty);
} });
});
});
</script>
</head>
<body>
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-increase="1" > + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{1}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-increase="0" > - </a>
</div>
</body>
<footer>
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
</script>
</footer>
守則控制器功能
public function ajaxl(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
if ($request->increase) {
//$cart->increment('qty');
$qty = 2;
} else {
//$cart->decrement('qty');
$qty = 0;
}
//echo"hello ajaxlara:";
return response()->json(array('qty'=> $id), 200);
}
}
這routes.php文件
Route::get('/ajax',function(){return view('online_help');});
Route::post('/getmsg','[email protected]');
當我點擊+或 - 時,該值不會改變,也不會出錯。 請任何人幫我
關於csrf是怎麼回事?你有沒有? – vitr
我添加了它並測試它,它使用一個簡單的代碼 –
我看不到任何csrf在你寫的代碼中,如果你不使用它,那麼你需要禁用VerifyCsrfToken中間件 – vitr