【问题标题】:Ajax request 500 error - Call to a member fucntion on nullAjax 请求 500 错误 - 在 null 上调用成员函数
【发布时间】:2021-03-08 04:48:27
【问题描述】:

我有我的阿贾克斯。 Symfony 中的方法,它发送特定表行中单击按钮的 id。

我的错误日志返回:

在 null 上调用成员函数 changeStatus()

这很奇怪,因为当我在控制器中 dump($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);
        }
      });
    }

【问题讨论】:

  • 您可以在帖子中添加您使用changeStatus 方法的文件吗?
  • 感谢重播。你能解释为什么这是相关的吗?文件中的其他方法除外。 @麦斯基
  • 错误出现在哪个文件的哪一行?
  • dump($entity) 的结果是什么?

标签: javascript php jquery ajax symfony


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-01-19
    • 2017-09-14
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2016-07-11
    • 2018-09-06
    • 2020-07-16
    相关资源
    最近更新 更多