【问题标题】:Create a record using modal bootstrap and ajax?使用模式引导程序和 ajax 创建记录?
【发布时间】:2017-12-15 20:01:16
【问题描述】:

我正在使用 Laravel 5.4 制作一个简单的博客。我想知道如何使用 ajax 和模式引导程序创建记录,以便每次添加记录时都不必重新加载页面?我尝试了网上的教程,但我仍然无法让它在我的项目上运行(因为我真的不擅长 JS)。

我目前的存储方式:

public function store(Request $request) {
        $input = $request->all();
        $validator = Validator::make($input, [
                    'title' => 'required|string'
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput()->with($this->addTagError);
        } else {
            $tag = Tag::create($input);
        }
        return redirect()->route('tagsindex')->with($this->addTagSuccess);
    }

路线:

Route::post('dashboard/tags', 'TagCon@store')->name('tagstore');

观点:

<div class="alert alert-info fade in">
   <h4>Manage Blog Tags From Here</h4>
     <p>
        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#addModal">Add a new Tag</button>
     </p>
     <!-- Add Modal start -->
     <div class="modal fade" id="addModal" role="dialog">
        <div class="modal-dialog">
        <!-- Modal content-->
           <div class="modal-content">
               <div class="modal-header">
                   <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add a new Tag</h4>
               </div>
               <form action="{{ route('tagstore') }}" method="POST" enctype="multipart/form-data">
                  <div class="modal-body">
                  {{ csrf_field() }}
                      <div class="form-group">
                         <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
                         <label class="control-label">Tag Name<span style="color: red">*</span> :</label>
                         <input type="text" name="title" id="title" class="form-control" value="{{old('title')}}" />
                         @if ($errors->has('title'))
                         <span class="help-block">
                         <strong>{{ $errors->first('title') }}</strong>
                         </span>
                         @endif
                         </div>
                      </div>
                   </div>
               <div class="modal-footer">
                  <button type="submit" class="btn btn-info"><span id="" class='glyphicon glyphicon-check'></span> Submit</button>
                  <button type="button" class="btn btn-warning" data-dismiss="modal"><span id="" class='glyphicon glyphicon-remove'></span> Cancel</button>
               </div>
               </form>
            </div>
         </div>
      </div>
   <!-- add modal code ends -->
    </div>

<div class="col-md-12">
                    <div class="table-responsive">
                        <table class="table table-dark mb30">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Tags Name</th>
                                    <th style="text-align: center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($tags as $indexKey => $t)
                                <tr>
                                    <td>{{ $indexKey+1 }}</td>
                                    <td><a href="{{ url('dashboard/tags/' . $t->titleslug) }}">{{$t->title}}</a> ({{$t->posts->count()}})</td>
                                    <td class="table-action">
                                        <a href="{{url('dashboard/tags/'. $t->id .'/edit')}}" class="tooltips" data-toggle="tooltip" data-placement="top" title="Edit">
                                            <button style=" background: none;">
                                                <i class="fa fa-edit" aria-hidden="true"></i>
                                            </button>
                                        </a>
                                        <a class="tooltips" data-toggle="tooltip" data-placement="top" title="Delete">
                                            <form action="{{route('tagdestroy', $t->id)}}" method="POST">
                                                <input type="hidden" name="_method" value="DELETE">
                                                <input type="hidden" name="_token" value="{{ csrf_token() }}" />
                                                <button type="submit" style=" background: none;" onclick="return confirm('Anda yakin ?');">
                                                    <i class="fa fa-trash-o" aria-hidden="true"></i>
                                                </button>
                                            </form>
                                        </a>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div><!-- table-responsive -->
                </div><!-- col-md-6 -->

上面的代码有效,但每次添加记录时它仍会重新加载页面。抱歉,我没有在这里放一个 ajax 代码,因为正如我之前所说,我什至不知道从哪里开始。我确信一个使用我的应用程序的例子就足以让我学习它,然后下次我自己创建它。

【问题讨论】:

    标签: ajax laravel laravel-5


    【解决方案1】:

    我将向您展示一个我在实际应用程序中构建的示例。虽然这是用 Laravel 5.2 构建的,但我相信你一定能弄明白。这是使用 Bootstrap、Javascript 和 jQuery 构建的。由于您似乎已经熟悉 Bootstrap,因此您可能需要查看以下链接。

    您将在下面找到一些您可能可以使用的代码片段。

    基本模态 HTML

    <div id="userModal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Create user</h4>
          </div>
          <div class="modal-body">
            <form id="userForm" class="form-horizontal">
                <div id="userFormErrorList" class="alert alert-danger">
                    <ul></ul>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="name">Name</label>
                    <div class="col-sm-10">
                        <input type="text" id="name" name="name" class="form-control">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="email">Email</label>
                    <div class="col-sm-10">
                        <input type="text" id="email" name="email" class="form-control">
                    </div>
                </div>
                {{ csrf_field() }}
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button id="saveUser" type="button" class="btn btn-primary" onclick="return false;">Save</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
    

    现在在同一页面上,您将需要 Javascript(和/或 jQuery)来发送 Ajax 请求。在这个例子中,我使用的是 jQuery。

    Javascript/jQuery

    $(document).ready(function() {
        // Hide the contact person form error list
        $('#userFormErrorList').hide();
    
        // Add save handler to modal form
        $('#saveUser').on('click', function () {
            var name = $('#name').val();
            var email = $('#email').val();
            var csrf = $('input[name=_token]').val();
    
            var url = "{{ route('users.store') }}";
            $.ajax({
                method: "POST",
                url: url,
                data: {
                    'name': name,
                    'email': email,
                    '_token': csrf
                },
            }).done(function(response) {
                // Do something with the data you got.
                // For example, add the data to the screen.
            }).fail(function(response) {
                // Clear the error list, since something went wrong.
                $('#userFormErrorList ul').html('');
                // Add the returned errors to list
                var object = $.parseJSON(response.responseText);
                $.each(object, function(key, value) {
                    $('#userFormErrorList ul').append('<li>' + value + '</li>');
                });
                // Show the list
                $('#userFormErrorList').slideDown();
            });
        });
    
        $('#userModal').on('show.bs.modal', function (event) {
            // Whenever the modal is opened, focus the cursor on the name field
            $('#name').focus();
        });
    
    });
    

    现在您可以看到,当有人点击保存按钮时,我们将需要处理通过 Ajax 获得的数据。

    PHP(控制器)

    public function overviewUsersStore(Request $request)
        {
            /* Validate data
            *  If the validation fails, there will be sent a failed response text.
            *  This enables us to show validation errors in the view itself 
            * (check out the part about the error list in Javascript)
            */
            $this->validate($request, [
                'name' => 'required|max:255',
                'email' => 'required|confirmed|email|unique:users',
            ]);
    
            // Store data
            $user = New User;
            $user->name         = $request->name;
            $user->email        = $request->email;
            $user->save();
    
            // IMPORTANT: Just return a simple string, or object, whatever, but DON'T redirect!
            // If you redirect, you won't get a proper response on your Ajax call.
            return 'stored';
        }
    

    这么多应该可以让您正确开始。如果您有任何问题,请随时发表评论。

    【讨论】:

    【解决方案2】:

    您需要阅读 AJAX 以了解如何添加此类功能。 The Mozilla Developer Network has some great resources to get you started.

    就目前而言,您的代码正在经历标准的提交-重新加载周期,这就是它仍然重新加载的原因。由于它有效(这很棒),您接下来的步骤将是添加 JavaScript 并重构您的服务器端代码。

    从逻辑上讲,您将要做的是使用 JavaScript 创建一个函数,该函数将中断表单的标准提交过程并向服务器发送单独的请求并使用其响应。此数据通常以 JSON 格式发送。

    如果您已经在使用 jQuery(如果您正在使用 Bootstrap,您可能就是这样),您可以使用它的 $.ajax 函数。如果没有,您可以使用 Axios 之类的东西,甚至可以使用 JavaScript 中内置的原版 XMLHttpRequest。您需要告诉浏览器停止标准进程,从表单中收集数据,并将其发送到服务器。

    然后您需要重构服务器端代码,使其不返回redirect() 函数,而是发送JSON Response

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2015-11-23
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多