【问题标题】:Returning a view with previous inputs using Laravel使用 Laravel 返回具有先前输入的视图
【发布时间】:2017-11-09 04:52:09
【问题描述】:

我有一个表单,在提交时会调用 AJAX 请求。此 ajax 请求对输入执行后端验证。如果检测到错误,它会显示错误消息。 因此,如果用户填写了 30 个字段,其中一个无效,我想返回所有这些输入并显示错误消息。

我的 Laravel 代码:

Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

$var= parse_str($m['inputs'], $output);//data from ajax is a string

if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){//if no error, return the next view
        return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
    }
    return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});

我的 Ajax 请求:

$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
        success: function(data){
            $('#tabShow').html((data.view));
        },
        error: function () {
            alert('error');
        }
    });
});

我能够成功接收到所有错误消息,但 withInput($output) 出于某种原因无法正常工作。感谢您的所有帮助。

【问题讨论】:

  • 可以给我们看看$output的内容吗?
  • 没问题! $output 只是一个关联数组: $output: [ '_token'=>...., 'TB1_course' =>[ '0'=>//user input 1 '1'=>//user input 2 ],所有其他输入]
  • 你为什么想要那个?由于您是通过 ajax 发布的,因此这些字段并没有真正被擦除(除非您明确编写擦除它们的 js)?但要回答你的问题 - 我很确定 ->withInput() 为输入设置了一个会话闪存变量。
  • 由于我正在用视图替换当前视图所在的 div。他们会被抹去。我的 html 看起来像:
    ,我的 ajax 正在用新视图(不带输入)替换该 div 内的所有 html(带输入)

标签: ajax laravel laravel-5


【解决方案1】:

'view' => view('template')->withInput()?

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 2019-01-26
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 2016-05-16
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多