Laravel 5中的Ajax发布请求返回错误500(内部服务器错误) [英] Ajax post request in laravel 5 return error 500 (Internal Server Error)

查看:299
本文介绍了Laravel 5中的Ajax发布请求返回错误500(内部服务器错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在laravel 5中测试的ajax(请参阅下文)

This is my test ajax in laravel 5 (refer below)

$("#try").click(function(){
    var url = $(this).attr("data-link");
    $.ajax({
        url: "test",
        type:"POST",
        data: { testdata : 'testdatacontent' },
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
});

和触发链接

<a href="#" id="try" data-link="{{ url('/test') }}">Try</a>

我的路线

Route::post('test', function()
{
    return 'Success! ajax in laravel 5';
});

但是当我在谷歌浏览器中运行控制台时,它给了我一个错误,它没有返回预期的响应返回成功! laravel 5'中的ajax;'

but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"

POST http://juliver.laravel.com/test 500(内部服务器错误)

POST http://juliver.laravel.com/test 500 (Internal Server Error)

我的代码有什么错误/问题?任何我想念的东西吗?

whats wrong/problem to my code? anything I'm missing?

推荐答案

虽然这个问题存在了一段时间,但没有给出可接受的答案,但我想向您指出解决方案.因为您使用的是ajax发送,并且大概仍在使用CSRF中间件,所以您需要在请求中提供一个附加的标头.

While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.

向每个页面(或主版面)添加一个元标记:<meta name="csrf-token" content="{{ csrf_token() }}">

Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">

并添加到您的javascript文件(或页面中的部分):

And add to your javascript-file (or section within the page):

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

请参见 https://laravel.com/docs/master/csrf #csrf-x-csrf-token 了解更多详细信息.

See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.

这篇关于Laravel 5中的Ajax发布请求返回错误500(内部服务器错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆