微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 401通过Ajax对laravel中的RESTful API进行Unauthorized DELETE请求

我使用laravel控制器创建了一个安静的API.我有一个PhotosController,它有一个用于删除资源的destroy($id)方法.我也有一段javascript代码向我的应用程序发送DELETE请求.结果应该是删除带有$id id的照片.但是laravel没有将我的请求路由到destroy方法.相反,它发送401 Unauthorized错误.

问题是我想通过Ajax向我的应用程序发送DELETE请求,但是laravel不会让我的请求被路由!

routes.PHP文件

Route::resource('photos', 'PhotosController');

破坏方法

public function destroy($id)
{
    try{
        unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
        Session::forget('photo');
        $msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
        return Response::json(array('success' => $msg));
    }catch (Exception $e){
        App::abort(500, $e->getMessage());
    }
}

我的Ajax请求:

$.ajax(
    {
        url: "/photos/" + name,
        method : "DELETE", // Or POST : result is the same
        data :{
            _token : $("input[name=_token]").val(),
            _method : 'DELETE'
        },
        success: function(data, textStatus, jqXHR ){
            parent.replaceWith("");
            toastr.success(data['success']);
            $("#overlay").hide();
        },
        beforeSend : function(jqXHR, settings ){
            $("#overlay").show();
        },
        error : function(jqXHR, textStatus, errorThrown ){
            toastr.error(jqXHR.responseText);
            $("#overlay").hide();
        }
    }
);

谢谢你的帮助.

解决方法:

我在Laravel应用程序中一直都是这样做的,没有任何问题.此代码允许用户在首先显示引导程序确认对话框时通过AJAX删除资源.代码按事件发生的顺序排列.

查看资源要删除

<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
    <i class="fa fa-trash fa-lg"></i>
</a>

JQUERY提出确认模式

$('.delete-plan').on('click', function(e) {
    e.preventDefault();

    var data = {
        'route':        $(this).attr('href'),
        'redirect':     $(this).data('redirect'),
        'modal_title':  'Delete Plan',
        'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
        'lang':         $(this).data('lang')
    };

    loadDestroyModal(data);
});

function loadDestroyModal(data) {
    $.get('/ajax/destroy-modal', { data: data }, function(modal) {
        $('body').append(modal);
        $('#destroy-modal').modal('show');
    });
}

AJAX控制器

// routed by /ajax/destroy-modal
public function destroyModal() {
    $data = Input::get('data');

    $params = [
        'route'    => $data['route'],
        'redirect' => $data['redirect'],
        'title'    => $data['modal_title'],
        'content'  => $data['content_view'],
        'lang'     => $data['lang']
    ];

    return View::make('_helpers.modal-destroy', $params);
}

DESTROY CONFIRMATION MODAL(_helpers.modal-destroy)

<div id="destroy-modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true"><i class="fa fa-times"></i></span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">{{ $title }}</h4>
            </div>
            <div class="modal-body">
                {{ $content }}
            </div>
            <div class="modal-footer">
                <button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
                data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

JQUERY处理破坏方法并重新发送闪存消息

$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
    var redirect = $(this).data('redirect');
    var lang     = $(this).data('lang');

    $(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');

    $.ajax({
        'url':     $(this).data('route'),
        'type':    'DELETE',
        'success': function(response) {
            if (response) {
                redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
            } else {
                redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
            }
        }
    });
});

计划控制器

public function destroy($id)
{
    try
    {
        Stripe::plans()->destroy(['id' => $id]);

        return Response::json(TRUE);
    }
    catch (Exception $e)
    {
        return Response::json(FALSE);
    }
}

请注意改变

function redirectWithFlashMessage(redirect, type, status, lang) {
    var params = {
        type:   type,
        status: status,
        lang:   lang
    };

    $.get('/ajax/flash', params, function(response) {
        window.location.href = redirect;
    });
}

AJAX控制器(使用Flash重定向)

public function flashData() {
    $message_type = 'success' == Input::get('status') ? 'success' : 'failure';

    $message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];

    Session::flash($message_type, $message);

    return ['status' => $message_type, 'message' => $message];
}

这是很多代码,但一旦设置它就很容易复制.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐