Laravel 4 的 Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20152803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:41:14  来源:igfitidea点击:

Ajax for laravel 4

phpjqueryajaxlaravellaravel-4

提问by Silverfall05

I'm trying to set up ajax for laravel, but it won't work. I have controller for posting comments. javascript which blocks the submit button and sends ajax which is returning 500 error

我正在尝试为 laravel 设置 ajax,但它不起作用。我有发布评论的控制器。阻止提交按钮并发送返回 500 错误的 ajax 的 javascript

public function postComment()
{
    if (Request::ajax()) 
    {
        return Response::json(['blah' => 'ohhh']);
        }
}

    $('#submit_comment').click(function (e)
{
    e.preventDefault();

    $.ajax({
        type : "POST",
        url : "http://page.dev/posts/comment",
        data : 
        {
            comment : $("#comment_area").text()
        }
    });

});

<script type="text/javascript">var comment = "{{URL::action('PostsController@postComment')}}"; </script>

What it returns is 500 internal server error

它返回的是 500 内部服务器错误

UPD:

更新:

    Route::get('posts/{id}', ['as' => 'post', 'uses' => 'PostsController@getShow'])->where('id', '\d+'); // Where id == number
Route::get('category/{id}', ['as' => 'category', 'uses' => 'PostsController@getCategory'])->where('id', '\d+');

SOLUTION:I used in constructor csrf protection. after i removed csrf protection from postComment it worked for me Route::controller('posts', 'PostsController');

解决方案:我在构造函数 csrf 保护中使用。在我从 postComment 中删除 csrf 保护后,它对我有用 Route::controller('posts', 'PostsController');

回答by Dave

It is difficult to to offer advice without seeing your route, controller, view code neatly separated. However, this is the bare minimum necessary to achieve your desired outcome:

如果没有看到你的路由、控制器、视图代码整齐地分开,就很难提供建议。但是,这是实现预期结果所需的最低限度:

In your routes.php

在你的routes.php

Route::post('/comment', function()
{
    return Response::json(['blah' => 'ohhh']);
});

In your view:

在您看来:

$.ajax({
    type : "POST",
    url : "comment",
});

if you are getting a 500 response then it is likely that you have a problem with your route to controller@postComment.

如果您收到 500 响应,那么您到 controller@postComment 的路由可能有问题。