Laravel-Ajax支持的页面,也有发布引起问题的表单


Laravel - Ajax Powered Pages and also have forms that Post causing issues

我正在构建一个通过ajax加载页面的网站,我有一个通过ajax发布的联系表单,所以我认为它是由我的发布路线触发的。。我只是在寻找最好的方法来区分页面导航帖子和页面上的表单帖子,这样它们就不会冲突。联系人页面的路线如下

Route::any('/contact',   function(){
    return view('frontend.contact');
});
Route::post('/contact', array( 'as' => 'contactform.create',  'uses' => 'ContactFormController@validateandsave'));

并且形式如下所示

{!! Form::open(array('url' => '/contact',  'route' => 'contactform.create', 'files' => false,  'method' => 'post', 'id'=>'updateform' ,'role'=>"form" )) !!}   
<span class="input input--kozakura">
{!! Form::text('full_name', '', array('class' => 'full_name input__field input__field--kozakura')) !!}
</span>
<span class="input input--kozakura">
{!! Form::email('email', 'paddy@gmail.com', array('class' => 'email input__field input__field--kozakura')) !!}
</span>
<span class="input input--kozakura">
{!! Form::text('current_website', 'www.lassiemarlowe.com', array('class' => 'current_website input__field input__field--kozakura')) !!}
</span>
<div class="submit-btn-wrapper">
{!! Form::submit('submit') !!}
</div>
{!! Form::close() !!}

那么,如何区分页面ajax帖子和表单ajax帖子呢?

将post定义放在另一个定义之前:

Route::post('/contact', array( 'as' => 'contactform.create',  'uses' => 'ContactFormController@validateandsave'));
Route::any('/contact',   function(){
                return view('frontend.contact');
            });

使用路由组是区分路由的好方法。我的解决方案是这样的。

// all normal routes in website here
Route::any('contact', function(){
    return view('frontend.contact'); // this will produce example.com/contact
});
// all ajax call
Route::group(['prefix' => 'ajax'], function () {
    Route::post('contact', 'ContactFormController@validateandsave') // this will produce example.com/ajax/contact
});

也使用操作('ControllerName@methodName')生成表单'action'属性的url。这将根据您的router.php文件动态更改

请参阅此处的详细信息:https://laravel.com/docs/5.2/routing#route-组https://laravel.com/docs/5.2/helpers#method-动作

从您对@AngadDubey的回答的最新评论来看,问题似乎不是两个路由(post和any)冲突,而是您实际上需要两个不同的处理程序来处理AJAX XHR post和普通浏览器形式的HTTP post。

据猜测,这是因为,尽管表单将以类似的方式处理,但根据发生的情况,传递错误或成功消息的方式将有所不同

我想说的是,不要真的把它们分开,而是在你需要归还东西的时候,在这个动作中进行一些检测。因此,正常处理POST输入(因为正常表单和AJAX表单应该是一样的,对吧?),但在返回响应时,使用类似app('request')->ajax()的东西来确定请求是否通过XHR。

或者,如果确实无法使用相同的验证和处理代码进行处理,则可以使用相同的检测来拆分处理。