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

查看:28
本文介绍了laravel 5 中的 Ajax post 请求返回错误 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 中的 ajax 5';"

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 post 请求返回错误 500(内部服务器错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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