方法不允许错误405发布ajax请求发布路由

时间:2019-01-04 15:02:34

标签: javascript ajax laravel-5 routes

当我尝试通过ajax发布请求发布到数据库以发布路由时,出现了405错误,方法错误。请帮助

$.ajaxSetup({
    headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') } 
});

$.ajax({
    url: '{{url("HeatMapCoordinates")}}',
    data:{
        "finalPointArray" : finalPointsMap,
        "tourId":tourId,
        "picWidth":picWidth,
        "picName":picName
    },
    async:true,
    type:'post',
    success:function(response){
        console.log("coordinates sent");
        finalPointsMap=[];
        pointsMap=[];
        pointsMap.push(initialPoint);
    },
    error:function(e){
        console.log("error");
        console.log(e);
    }
});

我也尝试过

url: '{{route("HeatMapCoordinates.store")}}',

但是它也不起作用,我的路线是:

Route::resource('/HeatMapCoordinates','HeatMapCoordinatesController');

我的控制器功能:

 public function store(Request $request)
{   
    $this->validate($request, array(
        'tourId'     => 'required',
        'picWidth' => 'required',
        'picName'  => 'required',
        'finalPointArray'  => 'required',

    ));
...
return 'stored';
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

$(document).ready(function(){

 $('#your_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"{{ route('HeatMapCoordinates_store') }}",
   method:"POST",
   data: new FormData(this),
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    console.log(data);
    // ANY CODE HERE
    $('#result').html(data.result);
   },
   error:function(data){
    console.log(data);
    $('#result').html('No result. We have an ERROR ...');
    }
  })
 });

});

并使用如下形式:

<form method="POST" id="your_form">
    <input type="text" name="finalPointsMap">
    <input type="text" name="tourId">
    <input type="text" name="picWidth">
    <input type="text" name="picName">

    <input type="submit" name="go" value="Submit">
</form>

使用此<div>来显示结果:

<div id="result"></div>

然后之后您的<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>

使用此路线

Route::post('/HeatMapCoordinates/store','HeatMapCoordinatesController@store')->name('HeatMapCoordinates_store');

并在 Controller 中使用此功能:

public function store(Request $request)
{   
    $validator = $this->validate($request, [
        'tourId'     => 'required',
        'picWidth' => 'required',
        'picName'  => 'required',
        'finalPointArray'  => 'required'
    ]);

    # RETURN ERRORS AS JSON
    if ($validator->fails()) {
       return response()->json([
            'result' => 'ERROR: ' // USE $validator->errors() for example ... 
        ]);
    }

    # USE YOUR INPUTS HERE, LIKE THIS 
    $id = $request->tourId;

    return response()->json([
        'result' => 'Good, ID is : '.$id
    ]);
}

请告诉我它是否有效:)