如何在Laravel 5.3中修复AJAX模态形式

时间:2019-04-19 17:29:23

标签: ajax bootstrap-modal laravel-5.3

我已将我的应用程序从Laravel 4.2升级到Laravel 5.3。在列出引用的索引页面上,我有一个AJAX模态表单来编辑或查看引用的登录凭据。在Laravel 4.2中可以正常工作,但是我一生无法在5.3中使用它。经过大约5个小时的Google搜索和尝试其他尝试,我想将其发布在这里,以便比我更有经验的人可以为我指明正确的方向。

这是索引页上的链接:

<a style="cursor: pointer; " title= "Login Credentials" data-loopback="cit-pg-1" data-citationid="1079" class="getCitationdetails"><span class="glyphicon glyphicon-lock " title="Login Credentials"></span></a>

这是JavaScript:

<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
    var citationid = $(this).data('citationid');
    var loopback = $(this).data('loopback');
    $.ajax({
        url : '/citation-password',
        type:'post',
        data : {citationid :citationid, loopback :loopback},
        success:function(resp){
            $('#AppendLoginDetails').html(resp);
            $('#LoginCredentialsModal').modal('show');
            $('.loadingDiv').hide();
        },
        error:function(){
            alert('Error');
        }
    })
})

这是我的路线:

    Route::match(['get', 'post'], '/citation-password', 'CitationsController@citationpassword');

这是Controller方法,该方法在get上生成表单并将数据保存在post上:

    public function citationpassword()
{
    if (Request::ajax()) {
        $data = Request::all();
        if (!$data['citationid']) {
            return redirect('/citations')
                ->with('flash-danger', 'Missing citation id for Login credentials form!!');
        }
        // Save loopback variable if we have it in order to return user to the page where they came from; default return location is citations
        $loopback = 'citations';
        if (array_key_exists("loopback", $data)) {
            $loopback = $data['loopback'];
        }

        $getcitationdetails = Citation::where('id', $data['citationid'])->select('id', 'site_id', 'username', 'password', 'login_email', 'login_notes')->first();
        $getcitationdetails = json_decode(json_encode($getcitationdetails), true);
        $getsitedetails = Site::where('id', $getcitationdetails['site_id'])->select(
            'id',
            'directory_username',
            'directory_password',
            'security_questions',
            'email_account',
            'email_account_password',
            'email_account_name',
            'google_user',
            'google_pwd',
            'name_of_google_account'
        )->first();
        $getsitedetails = json_decode(json_encode($getsitedetails), true);
        $response ="";
        $response .= '<form action="'.url('/citation-password').'" method="post">
                        <div class="modal-body">';
        if (!empty($getsitedetails['directory_username'])) {
            $response .= '<div class="form-group">
                                <label for="recipient-name" class="col-form-label">Default login credentials for this site:</label>
                                <p>Username: '.$getsitedetails['directory_username'].'
                                <br />Password: '.$getsitedetails['directory_password'].'
                                <br />Email account: '.$getsitedetails['email_account'].'
                                <br />Email password: '.$getsitedetails['email_account_password'].'
                                <br />Name on email account: '.$getsitedetails['email_account_name'].'
                                <br />Default security questions: '.$getsitedetails['security_questions'].'</p>
                                <p>Gmail account: '.$getsitedetails['google_user'].'
                                <br />Gmail password: '.$getsitedetails['google_pwd'].'
                                <br />Name on Gmail account: '.$getsitedetails['name_of_google_account'].'</p>
                            </div>';
        }
                    $response .= '
                        <input type="hidden" name="_token" value="'.csrf_token() .'" />
                        <input type="hidden" name="citation_id" value="'.$data['citationid'].'" />
                        <input type="hidden" name="loopback" value="'.$loopback.'" />
                        <div class="form-group">
                            <label for="recipient-name" class="col-form-label">Username:</label>
                            <input type="text" class="form-control" name="username" value="'.$getcitationdetails['username'].'" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="message-text" class="col-form-label">Password:</label>
                            <input type="text" class="form-control" name="password" value="'.$getcitationdetails['password'].'" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="message-text" class="col-form-label">Login email used:</label>
                            <input type="text" class="form-control" name="login_email" value="'.$getcitationdetails['login_email'].'" autocomplete="off">
                        </div>
                        <div class="form-group">
                            <label for="message-text" class="col-form-label">Login notes:</label>
                            <textarea class="form-control" style="height:130px;" name="login_notes">'.$getcitationdetails['login_notes'].'</textarea>
                        </div>

                </div>
                <div class="modal-footer">
                <button type="submit" class="btn btn-success" id="success">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Cancel</button>
                </div>
                </form>';
                return $response;
    } else {
        // The popup modal has posted back here; process the data
        $data = Request::all();
        // Handle & translate loopback; returning user to the page where they came from
        $loopback = 'citations';
        if ($data['loopback']) {
            $loopback = $data['loopback'];
            // Translate pages it came from
            $trackLoopback = new trackLoopback();
            $loopback = $trackLoopback->translate($loopback);
        }
        $updatecitation = Citation::find($data['citation_id']);
        $updatecitation->username = $data['username'];
        $updatecitation->password = $data['password'];
        $updatecitation->save();
        return redirect($loopback)
            ->with('flash-success', 'Login credentials have been updated successfully!');
    }
}

为了找出错误,我什至简化了控制器中的表格,如下所示:

    public function citationpassword()
{
    if (Request::ajax()) {
        return '<p>This is the modal form!</p>';

    } else {
        // The popup modal has posted back here; process the data
        $data = Request::all();
        // Handle & translate loopback; returning user to the page where they came from
        $loopback = 'citations';
        if ($data['loopback']) {
            $loopback = $data['loopback'];
            // Translate pages it came from
            $trackLoopback = new trackLoopback();
            $loopback = $trackLoopback->translate($loopback);
        }
        $updatecitation = Citation::find($data['citation_id']);
        $updatecitation->username = $data['username'];
        $updatecitation->password = $data['password'];
        $updatecitation->save();
        return redirect($loopback)
            ->with('flash-success', 'Login credentials have been updated successfully!');
    }
}

并简化了到达此路线:

    Route::get('/citation-password', 'CitationsController@citationpassword');

但是当我单击链接时,我得到的只是一个弹出式通知“错误”。

我对AJAX没有经验。我如何在Laravel 5.3中显示表格?

和/或,如何更改JavaScript函数,使其显示实际错误而不是“错误”通知? (我尝试了在StackOverflow上发现的许多方法来显示错误,但所有方法均未引起错误通知;只是空白页。而且,我也未能成功地使我的Firefox调试器显示错误。) / p>

谢谢!

1 个答案:

答案 0 :(得分:0)

调试JavaScript的正确方法是通过以下方式发布错误:

<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
    var citationid = $(this).data('citationid');
    var loopback = $(this).data('loopback');
    $.ajax({
        url : '/citation-password',
        type:'post',
        data : {citationid :citationid, loopback :loopback},
        success:function(resp){
            $('#AppendLoginDetails').html(resp);
            $('#LoginCredentialsModal').modal('show');
            $('.loadingDiv').hide();
        },
        error: function(xhr, ajaxOptions, thrownError) {
             alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }

    })
})

一旦这样做,您将看到错误与表单缺少CsrfToken有关。 [实际的错误消息来自Laravel框架:Illuminate \ Session \ TokenMismatchException:位于文件/home/reviewsites/moxy53/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php,在第6行中] get和post动词都使用相同的路径,Laravel要求CsrfToken 之前生成具有Csrf字段的形式。

有可能(但建议!)通过编辑App \ Http \ Middleware \ VerifyCsrfToken.php将该路径从CSRF保护中排除,但以下情况除外:

    /**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    '/citation-password',
];  

但是,更好的方法是添加令牌。正确的是,由于您使用的是post方法将数据值发送到控制器,因此您不能使用控制器在表单中生成令牌字段。因此,解决方案是将html从控制器中取出并放入刀片中。这些行:

$response .= '<form action="'.url('/citation-password').'" method="post">
    <div class="modal-body">';

        ...
    </div>
</form>';

不应出现在控制器生成的$ response中,而应出现在刀片本身的模式div中。 之后,您可以在刀片中添加CSRF字段,从而:

<form action="{{url('/citation-password')}}" method="post">
    {{ csrf_field() }}
    <div class="modal-body" id="AppendLoginDetails">
    </div>
</form>