Php Laravel Ajax验证工作正常[422状态],但如果验证成功且数据已插入数据库,则页面不会重定向

Php Laravel Ajax验证工作正常[422状态],但如果验证成功且数据已插入数据库,则页面不会重定向,php,ajax,laravel,validation,Php,Ajax,Laravel,Validation,Laravel Ajax验证工作正常[422状态],但如果验证成功且数据已插入数据库,则页面不会重定向 有一个错误[422无法处理的实体],但我在代码中解决了如下问题 我试图解决这个问题,它可以在不启用ajax验证的情况下工作并成功重定向 // Routes Route::name('authorCreatePost')->get('post/create', 'AuthorController@createPost'); Route::name

Laravel Ajax验证工作正常[422状态],但如果验证成功且数据已插入数据库,则页面不会重定向

有一个错误[422无法处理的实体],但我在代码中解决了如下问题

我试图解决这个问题,它可以在不启用ajax验证的情况下工作并成功重定向


    // Routes

        Route::name('authorCreatePost')->get('post/create', 'AuthorController@createPost');
        Route::name('_authorCreatePost')->post('post/create', 'AuthorController@_createPost');


您只需从控制器返回成功状态

response()->json(['success' => 'success'], 200);
response()->json(['redirect' => route('authorCreatePost')], 200);
然后在ajax调用的成功函数中重定向

$.ajax({
    url: "{{ route('_authorCreatePost') }}",
    method: 'post',
    data: {
        //..
    },
    success: function(response){
        window.location.href = "{{ route('authorCreatePost') }}";
    },
    error: function(data){
        //...
    },
});
或者,您可以从控制器返回要重定向的路由

response()->json(['success' => 'success'], 200);
response()->json(['redirect' => route('authorCreatePost')], 200);
然后重定向到ajax调用成功函数响应中的路由

$.ajax({
    url: "{{ route('_authorCreatePost') }}",
    method: 'post',
    data: {
        //..
    },
    success: function(response){
        window.location.href = response.redirect;
    },
    error: function(data){
        //...
    },
});

在ajax请求中,您不能重定向。您可以返回一个响应。我在成功之前尝试过:函数(响应){window.location.href=“{{route('authorCreatePost')}}”}”;},但很抱歉,我在“window.location.href”中错过了“window”。谢谢,现在可以用了
$.ajax({
    url: "{{ route('_authorCreatePost') }}",
    method: 'post',
    data: {
        //..
    },
    success: function(response){
        window.location.href = response.redirect;
    },
    error: function(data){
        //...
    },
});