javascript - Ajax 请求 500 错误 - 在 null 上调用成员函数
问题描述
我有我的阿贾克斯。Symfony 中的方法,它发送特定表行中单击按钮的 id。
我的错误日志返回:
在 null 上调用成员函数 changeStatus()
这很奇怪,因为当我在控制器中转储($id)时,它显示了该实体对象的 id,所以我无法弄清楚问题出在哪里。
这是我的方法:
/**
* @Route("/my-entity-route/{id}", name="change_status", options={"expose"=true})
*/
public function changeStatus($id)
{
// dump($id);die; -- shows id number
$entity = $this->entityManager->getRepository(MyEntity::class)->find($id);
$entity->setStatus(MyEntity::STATUS_CHANGE);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}
还有我的按钮:
<button type="button" data-entity_id="{{ item.id }}" class="change">Switch Status</button>
js文件中的方法:
$(".change").click(function(ev, el){
var id = $(this).data("entity_id");
if (confirm("Are you sure that you want change status?")) {
changeToNewStatus(id);
}
});
function changeToNewStatus(id) {
$.ajax({
type: 'PATCH',
url: "/my-entity-route/"+id,
processData: false,
contentType: 'application/json-patch+json',
success: function () {
console.log('success!')
},
error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
解决方案
似乎您尝试从数据库中获取的实体不存在,您确定您请求具有正确 ID 的现有实体吗?
此外,最好触发 404 而不是获取空指针:
/**
* @Route("/my-entity-route/{id}", name="change_status", options={"expose"=true})
*/
public function changeStatus($id)
{
$entity = $this->entityManager->getRepository(MyEntity::class)->find($id);
if (!$entity) {
throw $this->createNotFoundException('The entity does not exist');
}
$entity->setStatus(MyEntity::STATUS_CHANGE);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}
推荐阅读
- c# - 无法从 Unity 中的另一个脚本设置 UI 文本
- css - 在 vue.js 中,我只能在当前路由器下更改父元素的 css 吗?
- amazon-web-services - AWS 最佳架构模型
- libgdx - Facebook 与 Libgdx 的集成 java.lang.AbstractMethodError
- php - 如何在sections.php上返回fetch的值
- laravel-5 - 未定义变量:数据(查看:C:\xampp\htdocs\lsapp\resources\views\complete.blade.php)
- python - Python-MySQL:如何在 python 脚本中创建选择(where 子句)查询?
- android - 动态更改视图类型 RecylerView
- c++ - glReadPixels 和 gluUnProject 无法正常工作
- git - 在 GitLab 中打开 Word 文件而不是下载