Laravel Ajax响应帖法

时间:2016-11-22 09:24:21

标签: php ajax laravel

当我使用get route时,我的代码工作正常。我只想用ajax发送数据,然后将其检索回来。

$('.link').click(function(){
        var c = $(this).text();
        var url = '{{route('home')}}';


        $.ajax({

            url:url,
            data:{'mydata' : c  }

        })
        .done(function(msg){
            console.log(msg['response']);
        });

    });

并在我的路线文件中:

Route::get('/home', function(Request $request){
return response()->json(['response' => $request['mydata']]);})->name('home');

当我在Route中使用get方法时,它工作正常。当我使用post时,我得到一个错误:405(Method Not Allowed)。 我在AJAX上使用方法:'post',我收到一个错误:500(内部服务器错误)

有人可以帮忙吗?谢谢。

2 个答案:

答案 0 :(得分:0)

使用帖子时,请更改路线。

Route::post('/home',

答案 1 :(得分:0)

这将有效:

$('.link').click(function(){
    var c = $(this).text();
    var url = '{{route('home')}}';


    $.ajax({
        type: "POST",
        url:url,
        headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        data:{'mydata' : c  }

    })
    .done(function(msg){
        console.log(msg['response']);
    });

});

在路线中

Route::post(...
相关问题