ajax - Laravel/Ajax DELETE:“在 null 上调用成员函数 delete()”
问题描述
正如标题所说,当我尝试使用 laravel/ajax 和控制器内部的函数删除我的数据时出现错误:
控制器:
public function destroy($category_id) {
$category_delete = HmsBbrCategory::find($category_id);
$category_delete->delete();
return response()->json([
'status'=>200,
'message'=>'Category Deleted!',
]);
}
表单和阿贾克斯:
`delete_category` is the id that opens the delete modal and `delete_category_btn` is the button that will delete the data.
<button type="submit" class="btn btn-primary btn-block delete_category_btn"></i>Yes</button>
<button type="button" value="${cat.category_id}" class="delete_category btn btn-outline-secondary"><i class="fas fa-trash"></i> Delete</button>
$(document).on('click', '.delete_category', function (e) {
e.preventDefault();
//click this button(delete_category) to get the value(category_id)
var cat_id = $(this).val();
// alert(cat_id);
$('#delete_cat_id').val(cat_id);
$('#deleteCategoryModal').modal('show');
});
$(document).on('click', '.delete_category_btn', function (e) {
e.preventDefault();
var cat_id = $('#delete_cat_id').val();
// alert(cat_id);
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "DELETE",
url: "/clinical/bbr-category-configuration-delete/"+cat_id,
dataType: "dataType",
success: function (response){
// console.log(response);
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#deleteCategoryModal').modal('hide');
}
});
});
路线:
Route::delete('/bbr-category-configuration-delete/{category_id}', [BBRCategoryConfigurationController::class,'destroy']);
注意事项:
- 我继续并在模态中显示了 category_id 以证明该表正在被检索。
删除按钮的第二个 ajax 函数:$(document).on('click', '.delete_category_btn', function (e)
,我还尝试显示 id,alert(cat_id);
以证明 id 在模态中仍然被识别:
即使 category_id 存在,在尝试删除后检查页面仍然显示:
message: "Call to a member function delete() on null"
我能做些什么来解决这个问题?谢谢你的帮助。
解决方案
$category_delete
对象为空。也许你发错了$category_id
。如果您在删除之前检查该类别是否存在,则可以避免该错误。
public function destroy($category_id) {
$category_delete = HmsBbrCategory::find($category_id);
if($category_delete) {
$category_delete->delete();
return response()->json([
'status'=>200,
'message'=>'Category Deleted!',
]);
}
return response()->json([
'status'=>404,
'message'=>'Category Not Found!',
]);
}
推荐阅读
- python - pyautogui 拒绝写变音符号
- performance - XGBoost 超参数调优性能指标
- python-3.9 - 我收到此错误: print("I am " + 187 + " years old") TypeError: can only concatenate str (not "int") to str
- php - 如何让用户生成 if/then/else 案例并用简单的 php/html 显示
- android - 更改 Fragment Android 后未触发 RegisterForActivityResult 回调
- python-3.x - 在 Django Todo App 中,每个用户如何拥有一组不同的任务?
- python - 在二进制图像中查找连接斑点坐标的有效方法
- javascript - 有没有办法将 Google Dialogflow 中整个聊天机器人对话的日志获取到 Firebase 数据库?
- python - 可迭代数据集在单个 epoch 后耗尽
- node.js - “TypeError:GridFsStorage 不是构造函数”