简体   繁体   English

尝试通过Laravel中的Ajax将数据发布到控制器时出现MethodNotAllowedHttpException

[英]MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. 我正在尝试通过laravel中的ajax将动态生成的数据发送到控制器。 When user select an option from the dropdown then along with selected option and other data should be sent to controller. 当用户从下拉菜单中选择一个选项时,应将其与选定的选项和其他数据一起发送到控制器。

I've tried to send data to controller when an option from dropdown is selected. 当从下拉列表中选择一个选项时,我尝试将数据发送到控制器。 But every time i try this error, 但是每次我尝试这个错误时

Symfony \\ Component \\ HttpKernel \\ Exception \\ MethodNotAllowedHttpException and in the error REQUEST_METHOD is GET Symfony \\ Component \\ HttpKernel \\ Exception \\ MethodNotAllowedHttpException并在错误中REQUEST_METHOD是GET

This is the where i call the ajax function 这是我调用ajax函数的地方

$(document).on('change', '.route-code-selector', function() {
      var selectorID = $(this).attr('id');
      addRoutePlanDetails(selectorID);
 });

AJAX function AJAX功能

function addRoutePlanDetails(selectorID) {
    var routePlanCode = document.getElementById("routeplanno").value;
    var driver = $("#selectDriver").val().split('|');
    var salesman = $("#selectSalesman").val().split('|');
    var router_01 = $("#selectRouter01").val().split('|');
    var router_02 = $("#selectRouter02").val().split('|');
    var vehicle_no = document.getElementById("enterVehicleNo").value;
    var route_code = document.getElementById(selectorID).value;
    var date = document.getElementById("date").value;

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
});
$.ajax({
    url: 'addNewRoute',
    method: 'POST',
    dataType: 'json',
    data: {
        routePlanCode: routePlanCode,
        driver: driver[1],
        salesman: salesman[1],
        router_01: router_01[1],
        router_02: router_02[1],
        vehicle_no: vehicle_no,
        route_code: route_code,
        date: date
    },
    success: function() {
        console.log("success");
    }
});
}

Route 路线

Route::group(['prefix' => 'admin'], function () {
    Voyager::routes();

    Route::get ('route-plan', 'RoutePlanController@index');
    Route::get ('excludePorterRes', 'RoutePlanController@excludePorterRes');
    Route::get ('retreiveRouteData', 'RoutePlanController@retrieveRouteCodeData');
    Route::get ('retreiveUserData', 'RoutePlanController@retreiveUserData');
    Route::get ('retreiveNewRouteData', 'RoutePlanController@retreiveNewRouteData');

    Route::post('addNewRoute', [
        'uses' => 'RoutePlanController@insertNewRoute',
        'as' => 'addNewRoute'
    ]);
});

controller 调节器

public function insertNewRoute(){

    $routeplan = new Routeplan;
    $user_email = auth()->user()->email;

    $routeplan->RouteplanCode = Input::get('routePlanCode');
    $routeplan->RouteCode = Input::get('route_code');
    $routeplan->DriverID = Input::get('driver');
    $routeplan->SalesmanID = Input::get('salesman');
    $routeplan->Routercode1 = Input::get('router_01');
    $routeplan->Routercode2 = Input::get('router_02');
    $routeplan->VehicleNo = Input::get('vehicle_no');
    $routeplan->Date = Input::get('date');
    $routeplan->Createuser = $user_email;
    $routeplan->Status = 'TEMP';

    $routeplan->save();
}

when user select an option all the data should be stored in the db. 当用户选择一个选项时,所有数据都应存储在数据库中。

尝试一次

url: '{{ route('addNewRoute') }}',

The issue is here: 问题在这里:

url: 'addNewRoute',

here you are calling the route in a wrong manner, use it like: 在这里,您以错误的方式呼叫路线,请按照以下方式使用:

url: '{{ url('admin/addNewRoute') }}',

you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin , so you have to append that to while calling it. 您必须调用url()方法,以便它可以创建正确的url格式,并且不要忘记addNewRouteadmin下分组,因此您必须在调用它时将其附加到。

You have used prefix for your routes. 您已为路由使用prefix So all your route in group will be prefix/uri . 因此,您在组中的所有路由都将是prefix/uri So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type 因此,在ajax调用中,您应该使用url: '{{ url('admin/addNewRoute') }}',并更改要type method

 $.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
    routePlanCode: routePlanCode,
    driver: driver[1],
    salesman: salesman[1],
    router_01: router_01[1],
    router_02: router_02[1],
    vehicle_no: vehicle_no,
    route_code: route_code,
    date: date
},
success: function() {
    console.log("success");
}
});

In ajax for specifying HTTP Verb use type not method . ajax用于指定HTTP Verb使用type不是method

If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. 如果ajax方法在外部javascript文件中运行,则应在blade (通常是布局刀片)中定义一个url变量,该变量在ajax调用方法上用作ajax请求url。 (before .js file is loaded); (在加载.js文件之前);

Example var url = '{{ route('addNewRoute') }}' 示例var url = '{{ route('addNewRoute') }}'

$.ajax({
    url: url',
    method: 'POST',
    dataType: 'json',
    data: {
        routePlanCode: routePlanCode,
        driver: driver[1],
        salesman: salesman[1],
        router_01: router_01[1],
        router_02: router_02[1],
        vehicle_no: vehicle_no,
        route_code: route_code,
        date: date
    },
    success: function() {
        console.log("success");
    }
});

If you using ajax in the blade, you can use directly route as ajax request url. 如果在刀片中使用ajax,则可以直接使用route作为ajax请求url。

$.ajax({
    url: "{{ route('addNewRoute') }}",
    method: 'POST',
    dataType: 'json',
    data: {
        routePlanCode: routePlanCode,
        driver: driver[1],
        salesman: salesman[1],
        router_01: router_01[1],
        router_02: router_02[1],
        vehicle_no: vehicle_no,
        route_code: route_code,
        date: date
    },
    success: function() {
        console.log("success");
    }
}); 

You forgot / in your routes. 您在路线中忘记了/

Route::group(['prefix' => 'admin'], function () {

Add / in admin/ 添加/admin/

Route::group(['prefix' => 'admin/'], function () {

Then you can try this in your ajax 然后您可以在ajax中尝试

url: '{{ url('admin/addNewRoute') }}',

or 要么

url: 'admin/addNewRoute',

Try if this will work. 尝试是否可行。

if your script is in blade file then use route() to set url in ajax: 如果您的脚本在刀片文件中,则使用route()在ajax中设置url:

$.ajax({
    url: '{{route('addNewRoute')}}',
    method: 'POST',
    dataType: 'json',
    ...
});

Try this: 尝试这个:

Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'. 请使用网址:“ {{route('addNewRoute')}}”而不是网址:“ addNewRoute”。

As many of you said.. I changed method to type.. And it still didn't work. 就像你们中许多人所说的那样。我将方法更改为类型,但仍然无法正常工作。 But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. 但是后来我查看了laravel日志(存储/日志),从日志中发现我的某些控制器语法不正确。 And that's why it still gave me the 500 error. 这就是为什么它仍然给我500错误的原因。 After I changed the syntax and do the corrections. 之后,我更改了语法并进行了更正。 It worked !! 有效 !! Anyways thanks for helping guys! 无论如何,感谢你们的帮助! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone. 即使您的ajax正确,如果有人遇到此错误,请查看laravel日志。希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM