Laravel - Ajax Powered Pages,还有Post导致问题的表单

时间:2016-04-02 21:42:32

标签: php ajax forms laravel laravel-5.2

我正在构建一个网站,其中页面通过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?

3 个答案:

答案 0 :(得分:0)

将帖子定义放在另一个之前:

Route::post('/contact', array( 'as' => 'contactform.create',  'uses' => 'ContactFormController@validateandsave'));

Route::any('/contact',   function(){

                return view('frontend.contact');

            });

答案 1 :(得分:0)

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

// 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
});

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

详情请见: https://laravel.com/docs/5.2/routing#route-groups https://laravel.com/docs/5.2/helpers#method-action

答案 2 :(得分:0)

根据您对@ AngadDubey的回答的最新评论看起来问题不在于两条路线(post和any)是冲突的,但实际上你需要两个不同的处理程序来处理AJAX XHR POST而不是普通的浏览器形式HTTP POST。

猜测这是因为,虽然表单的处理方式类似,但传递错误或成功消息的方式会有所不同,具体取决于发生的情况。

我想说实际上并没有把它们分开,而是在你需要回复的时候对这个动作进行一些检测。因此正常处理POST输入(因为普通表单和AJAX表单应该相同,对吧?)但是当返回响应时,使用类似app('request')->ajax()的内容来确定请求是否来自XHR。

或者,如果使用相同的验证和处理代码无法处理它们,您可以使用相同的检测来分割处理。