简体   繁体   English

AJAX发布请求不适用于Laravel

[英]AJAX Post request not working with Laravel

I can do this: 我可以做这个:

 $.ajax({
        type: "GET",
        async: true,
        url: '/someurl/',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });

Web: 网页:

Route::get('/someurl','MyController@myfunction');

And it works just fine, but when I try the same with post: 而且效果很好,但是当我在post上尝试相同时:

 $.ajax({
        type: "POST",
        async: true,
        url: '/someurl/',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });

Route::post('/someurl','MyController@myfunction');

I get a 405 method not allowed error message in the console 我在控制台中收到405方法不允许错误消息

POST using normal ajax need CSRF Token to be pass in POST Method 使用普通ajax的POST需要CSRF Token才能通过POST Method传递

in your ajax 在你的ajax中

 $.ajax({
        type: "POST",
        async: true,
        url: '/someurl/',
        dataType: 'json',  
        data : {"_token":"{{ csrf_token() }}"}  //pass the CSRF_TOKEN()
        success: function (data) {
            console.log(data);
        }
    });

or 要么

set head meta tag 设置头元标记

<meta name="csrf_token" content="{{ csrf_token() }}" />

set header ajax 设置标头ajax

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

Add another route with 添加其他路线

Route::post('/someurl','MyController@myfunction');

By the way u are not sending any data, in post we need to send data right.. 顺便说一句,你不发送任何数据,在后期我们需要正确发送数据。

Also check whether csrf token is being passed in data, if not as mentioned above try adding it manually. 还要检查是否在数据中传递了csrf令牌,如果不是如上所述,请尝试手动添加它。

If you are using {{Form...}} it would be automatically added to form data. 如果您使用的是{{Form...}} ,它将自动添加到表单数据中。

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

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