我是一名 PHP 開發人員,目前正在根據我的任務轉向 Laravel 框架,我必須使用 ajax 完成實時表,但我仍然遇到一個錯誤,即 CSRF 令牌不匹配錯誤,請幫助我解決我僅發布短代碼的錯誤JAVA腳本<script> function getMessage() { $.ajax({ //var data = {"_token": $('#token').val()}, type:'POST', url:'/getMsg', headers: {'XSRF-TOKEN': $('meta[name="_token"]').attr('content')}, success:function(data) { $("#msg").html(data.msg); } }); } </script>路線路徑Route::post('/getMsg','CustomerSearchController@doAjaxTest');控制器代碼public function doAjaxTest(){ $msg = "<b>Message over ajax This test is Successful</b>."; return response()->json(array('msg'=> $msg), 200);}HTML代碼<center> <input type = "hidden" name = "_token" value = '<?php echo csrf_token(); ?>'> <table> <tr> <td><label>Enter Place Name</label></td> <td><input type="text" class="form-control" id="placename" name="placename" placeholder="Name Of Place"/></td> </tr> <tr> <td> <input type="submit" value="Get Message" onclick="getMessage()" /> </td> </tr> </table> <br> <!-- <div class="panel panel-default table-responsive"> <div id="dataTag"><b>All the Details according to department will be displayed</b></div> </div> --> <div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div> </center>我不知道為什么當標頭包含令牌時它會顯示 CSRF 令牌不匹配,一旦解決我就可以進行一些實時操作,請幫忙
3 回答

一只名叫tom的貓
TA貢獻1906條經驗 獲得超3個贊
確保視圖頭部有元標記:
<meta name="csrf-token" content="{{ csrf_token() }}" />
然后你可以在加載 jQuery 庫后初始化一次,添加:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
嘗試使用解決方案
- 3 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
0/150
提交
取消