Ajax 调用在成功时返回 CSRF 令牌,而不返回消息


Ajax call returning CSRF-token on success and not returning messages

从PHP调用ajax时,这个问题工作正常,但我似乎无法让它与Laravel 5.2一起工作。 我要做的就是在提交表单时使用 AJAX 发送电子邮件。

这是我发送电子邮件routes.php条目:

Route::post('/send', 'CommsController@send');

这是我layout.blade.php文件:

<head>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
$( document ).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    ...
    $( "#send" ).button().click(function(event) {
        var form       = $( "#contact-form" ),
            postAction = form.attr('action'),
            isValid    = form.valid(),
            valSum     = $(".validation-summary");
        if ( isValid ) {
            var postData = {
                message_type: "contact"
                ,first_name: first_name.val()
                ,last_name: last_name.val()
                ,email: email.val()
                ,message: message.val()
            };
            // process the form
            $.ajax({
                type: "POST",
                // our data object
                url: postAction,        // the url where we want to POST
                data: postData
            })
            // using the done promise callback
            .done(function(data) {
                // log data to the console so we can see
                console.log(data); 
                // here we will handle errors and validation messages
                if ( ! data.success ) {
                    valSum.removeClass( "success" );
                    valSum.addClass( "validation-summary error" );
                    valSum.html( data );
                } else {
                    // $( ".validation-summary" ).html( "Message sent." );
                    valSum.html( data.message );
                }
            })
            // using the fail promise callback
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log(data);
                valSum.removeClass( "success" );
                valSum.addClass( "validation-summary error" );
                valSum.html( "Server Error: " + data.statusText + " processing your request, please contact Dorothea or report a bug." );
            });
            // stop the form from submitting the normal way and refreshing the page
            event.preventDefault();
        } else {
            return false;
        }
    });

最后是我的CommsController send()函数:

public function send(Request $request) {
    //check if its our form
    if ( Session::token() !== Request::get( 'csrf-token' ) ) {
        return Response::json( array(
            'message' => 'Unauthorized attempt to create setting'
        ));
    }
    $message_type = strval(Request::input('message_type'));
    $first_name = strval(Request::input('first_name'));
    $last_name = strval(Request::input('last_name'));
    $email = strval(Request::input('email'));
    $message = strval(Request::input('message'));
    $to  = "robinson.jeanine6@gmail.com";
    // subject
    $subject = "Dorothea - Contact Us";
    Mail::send('email.contact', ['request' => Request::all()], function ($message) use ($request) {
        $message->from($this->email, $this->email);
        $message->to($user->email, $user->email)->subject($subject);
    });
    $response = array(
        'status' => 'success',
        'message' => 'Message sent.',
    );
    return Response::json( $response );
}

这个问题与我在这里发布的问题有关,但是不是得到MethodNotAllowedHttpException,而是现在从 AJAX 调用返回的所有内容都是 CSRF 令牌值。

.done回调替换为 .success 以获取返回数据。

.success(function(data) {
    if (data.status != 'success' ) {
        valSum.removeClass( "success" );
        valSum.addClass( "validation-summary error" );
    }
    // eventually, print out the return message
    valSum.html(data.message);
})

只是想让所有试图帮助我的人都知道,如果我将帖子请求更改为获取请求,则在 Laravel 中发送电子邮件可以正常工作。

不太确定为什么会这样,所以如果有人能阐明为什么会是这种情况,那就太好了。