【发布时间】:2017-12-16 13:49:54
【问题描述】:
如何使用 ajax 从路由中调用 url?
路线:
Route::delete('dashboard/tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');
控制器:
public function destroy($id) {
$tag = Tag::findOrFail($id);
$tag->delete();
return response()->json($tag);
}
Ajax 代码:
$(document).on('click', '.delete-modal', function () {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('id'));
$('#title_delete').val($(this).data('title'));
$('#deleteModal').modal('show');
id = $('#id_delete').val();
});
$('.modal-footer').on('click', '.delete', function () {
$.ajax({
type: 'DELETE',
url: 'dashboard/tags/destroy/' + id,
data: {
'_token': $('input[name=_token]').val(),
},
success: function (data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index + 1);
});
}
});
});
它什么也不做可能是因为它没有调用正确的路线?但是,如果我将这个url: 'dashboard/tags/destroy/' + id, 更改为这个url: '{{ URL::route('tagdestroy') }}' + id,,它将返回一个错误Missing required parameters for [Route: tagdestroy] [URI: dashboard/tags/destroy/{tag}]
代码的错误部分在哪里?谢谢
已解决
现在可以工作了,将 ajax 函数中的 url 调用更改为 url: 'tags/destroy/' + id, 而不是 url: 'dashboard/tags/destroy/' + id, 。我不知道它为什么会起作用,删除方法 url 仍然定义为Route::delete('dashboard/tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');,而不是Route::delete('tags/destroy/{tag}', 'TagCon@destroy')->name('tagdestroy');。
【问题讨论】: