首页 > 解决方案 > 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);
        }
      });
    }

标签: javascriptphpjqueryajaxsymfony

解决方案


似乎您尝试从数据库中获取的实体不存在,您确定您请求具有正确 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();
    }
}


推荐阅读