我正在尝试从AJAX调用控制器,我得到了这个错误
MethodNotAllowedHttpException in RouteCollection.php line 218:
我已经尝试了很多,但无法追踪实际问题。
Route.php
/*Ajax Request for Category*/
Route::post('category','AjaxOperationController@category');
Route::post('category/{category}', 'AjaxOperationController@category');
header.blade.php
<script>
$(document).ready(function(){
$.ajax({
method:'post',
url:'/category',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
//$("#msg").html(data.msg);
alert(data.category_name);
}
});
});
</script>
AjaxOperationController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
class AjaxOperationController extends Controller
{
public function category(){
$category=DB::select('select category_name from categories');
echo $category;
return response()->json(array('category_name'=> $category));
}
}
答案 0 :(得分:1)
将csrf标记添加到元:
<meta name="csrf-token" content="{{ csrf_token() }}">
设置.ajaxSetup(这将在默认模板中设置,因此它包含在其他ajax请求的所有地方):
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
你的阿贾克斯:
$(document).ready(function(){
$.ajax({
type:'post',
url:'/category',
success:function(data){
//$("#msg").html(data.msg);
alert(data.category_name);
}
});
});
跟踪inspect元素中的网络选项卡以查看从请求中获得的响应,如果出现其他任何错误,这将有助于进一步调试
修改
将您的成功回复更改为:
success:function(data) {
for (var i = 0; i < data.length; i++) {
$('#msg').append(data.category_name[i].category_name)
}
}
控制器 命名空间App \ Http \ Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Categories;
class AjaxOperationController extends Controller
{
public function category(){
$categories = Categories::get();
return response()->json($categories);
}
}