php - 如何在Symfony 4中使用dataTables防止错误 “Invalid JSON response”?

标签 php json symfony error-handling datatables

我用symfony创建了一个DataTable:

src/Entity/User.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Table(name="app_users")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=191, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    public function __construct()
    {
        $this->isActive = true;
        // may not be needed, see section on salt below
        // $this->salt = md5(uniqid('', true));
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getSalt()
    {
        // you *may* need a real salt depending on your encoder
        // see section on salt below
        return null;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getRoles()
    {
        return array('ROLE_USER');
    }

    public function eraseCredentials()
    {
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt
        ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}

templates/homepage.html.twig
{% extends 'base.html.twig' %}

{% block title %}Symfony{% endblock %}

{% block body %}

<div class="wrapper">

{{ include('inc/navbar.html.twig') }}

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper" style="min-height: 866px;">

  <section class="content">
    <div class="row">
      <div class="col-xs-12">

        <div class="box">
          <!-- /.box-header -->
          <div class="box-body">

            <table id="users">
                  <thead>
                      <tr>
                          <th>ID</th>
                          <th>Username</th>
                          <th>email</th>
                      </tr>
                  </thead>
              </table>

          </div>
        </div>
      </div>
    </div>
  </div>


</div>
<!-- /.content-wrapper -->

</div>
<!-- ./wrapper -->

{% endblock %}

src/DataTables/UsersDataTable.php
<?php

namespace App\DataTables;

use DataTables\DataTableHandlerInterface;
use DataTables\DataTableQuery;
use DataTables\DataTableResults;
use Symfony\Bridge\Doctrine\RegistryInterface;

class UsersDataTable implements DataTableHandlerInterface
{
    protected $doctrine;

    /**
     * Dependency Injection constructor.
     *
     * @param RegistryInterface $doctrine
     */
    public function __construct(RegistryInterface $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(DataTableQuery $request): DataTableResults
    {
        /** @var \Doctrine\ORM\EntityRepository $repository */
        $repository = $this->doctrine->getRepository('AppBundle:User');

        $results = new DataTableResults();

        // Total number of users.
        $query = $repository->createQueryBuilder('u')->select('COUNT(u.id)');
        $results->recordsTotal = $query->getQuery()->getSingleScalarResult();

        // Query to get requested entities.
        $query = $repository->createQueryBuilder('u');

        // Search.
        if ($request->search->value) {
            $query->where('(LOWER(u.username) LIKE :search OR' .
                          ' LOWER(u.email) LIKE :search)');
            $query->setParameter('search', strtolower("%{$request->search->value}%"));
        }

        // Filter by columns.
        foreach ($request->columns as $column) {
            if ($column->search->value) {
                $value = strtolower($column->search->value);

                // "ID" column
                if ($column->data == 0) {
                    $query->andWhere('u.id = :id');
                    $query->setParameter('id', intval($value));
                }
                // "Username" column
                elseif ($column->data == 1) {
                    $query->andWhere('LOWER(u.username) LIKE :username');
                    $query->setParameter('username', "%{$value}%");
                }
                // "Email" column
                elseif ($column->data == 2) {
                    $query->andWhere('LOWER(u.email) LIKE :email');
                    $query->setParameter('email', "%{$value}%");
                }
            }
        }

        // Order.
        foreach ($request->order as $order) {

            // "ID" column
            if ($order->column == 0) {
                $query->addOrderBy('u.id', $order->dir);
            }
            // "Username" column
            elseif ($order->column == 1) {
                $query->addOrderBy('u.username', $order->dir);
            }
            // "Email" column
            elseif ($order->column == 2) {
                $query->addOrderBy('u.email', $order->dir);
            }
        }

        // Get filtered count.
        $queryCount = clone $query;
        $queryCount->select('COUNT(u.id)');
        $results->recordsFiltered = $queryCount->getQuery()->getSingleScalarResult();

        // Restrict results.
        $query->setMaxResults($request->length);
        $query->setFirstResult($request->start);

        /** @var \AppBundle\Entity\User[] $users */
        $users = $query->getQuery()->getResult();

        foreach ($users as $user) {
            $results->data[] = [
                $user->getId(),
                $user->getUsername(),
                $user->getEmail(),
            ];
        }

        return $results;
    }
}

src/Controller/DataTableController.php
<?php

namespace App\Controller;

use DataTables\DataTablesInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

/**
*
* @Route("/users", name="users")
*
* @param Request $request
* @param DataTablesInterface $datatables
* @return JsonResponse
*/

class DataTableController extends Controller
{

  const ID = 'users';

  public function usersAction(Request $request, DataTablesInterface $datatables): JsonResponse
  {
    try {
      // Tell the DataTables service to process the request,
      // specifying ID of the required handler.
      $results = $datatables->handle($request, 'users');

      return $this->json($results);
    }
    catch (HttpException $e) {
      // In fact the line below returns 400 HTTP status code.
      // The message contains the error description.
      return $this->json($e->getMessage(), $e->getStatusCode());
    }
  }

}

但是我收到错误消息:

DataTables warning: table id=users - Invalid JSON response.



我进行了网络分析,但似乎一切正常:

enter image description here

最佳答案

您的请求类型为GET,因此您可以将请求url直接粘贴到浏览器中,然后您将看到响应是否为有效的JSON。无效的JSON响应意味着您的请求结果不是JSON,可能是错误或错误。

关于php - 如何在Symfony 4中使用dataTables防止错误 “Invalid JSON response”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240692/

相关文章:

symfony - 使用 Vagrant+Symfony 应用程序在 PHPStorm 中打开文件

symfony - 错误参数 Twig with Path() Symfony 2

php+symfony 5.0.x 扩展抽象类和同时实现接口(interface)时自动加载问题

php - 如何在不使用 API key 的情况下获取所有谷歌字体的列表?

php - fatal error : Call to undefined function sqlsrv_connect() in C:\xampp\htdocs

php - 使用 Doctrine 的 Symfony2 抽象类多重继承

php - 使用 dropzone 在一个请求中上传多个文件时遇到问题

json - 在 Erlang [Mochijson] 中正确解析单元素 JSON 列表?

python - 使用 python 解析 JSON 以根据条件获取值

javascript - Google Calendar 嵌套 JSON -- 无法读取未定义的属性 'length'