无法解析来自服务器的JSON数据。这是由

时间:2017-02-11 10:54:52

标签: mysql json zend-framework datatable warnings

请帮帮我。我遇到了一个DataTable警告,例如" DataTables警告:无法解析来自服务器的JSON数据。这是由JSON格式错误引起的。"在Zend框架中使用PHP,JSON编码。

此警告仅在表为空时发生,但此问题仅在我在sql查询中使用group关键字时出现,如果我不使用group关键字,那么它只从表中提供一条记录,但表有更多记录也。当我使用以下查询输出时,显示所有记录只有表有数据,如果没有数据表警告将显示。 // sql查询(models / table / product.php)

    public function fetchAllProductItems() {
$oSelect = $this->select()
                ->setIntegrityCheck(false)
                ->from(array("p" => "products","b" => "bid"), ('*'))
                ->joinLeft(array("b" => "bid"), "b.product_id=p.product_id", array('bid_id','bid_amount'))
                ->joinInner(array("e" => "employees"), "e.employee_id=p.employee_id",array('ename'))
                ->where("p.verified = ?", "Yes")
                ->where("p.sold_out = ?", "No")
                ->group('p.product_id')
                ->having("p.sale_end_date >= ?", date("Y-m-d"));
        return $oSelect;
    }

// JSON编码(模块/出售/控制器/ apicontroller)

public function getProductsAction()
{

     $oProductModel = new Application_Model_Db_Table_Products();
     $oSelect = $oProductModel->fetchAllProductItems();
     echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name', 'brand', 'conditions', 'about','image_path', 'reserved_price', 'Max(b.bid_amount) as amount')));

}

如果表中有多个记录,则下面的查询将只显示一条记录。如果表格是空的,那么我将来#34;表信息中没有数据可用来#34;。

// sql query(models / table / product.php)

 $oSelect = $this->select()
                ->setIntegrityCheck(false)
                ->from(array("p" => "products","b" => "bid"), ('*'))
                ->joinLeft(array("b" => "bid"), "b.product_id=p.product_id", array('bid_id','bid_amount'))
                ->joinInner(array("e" => "employees"), "e.employee_id=p.employee_id",array('ename'))
                ->where("p.verified = ?", "Yes")
                ->where("p.sold_out = ?", "No")

                ->where("p.sale_end_date >= ?", date("Y-m-d"));

1 个答案:

答案 0 :(得分:0)

正确的方法是添加" ViewJsonStrategy"到你的模块的配置,并将你的ViewModel标记为“终端”。

类似的东西:

public function getProductsAction()
{   
     $oProductModel = new Application_Model_Db_Table_Products();
     $oSelect = $oProductModel->fetchAllProductItems();
     //ViewModel requires one array
     $data = ['result'=>$this->_helper->DataTables($oSelect, ...)];
     $view = new ViewModel($data)->setTerminal(true);
}

我在GitHub上有一个可能有帮助的例子:

https://github.com/fmacias/SMSDispatcher

官方文档链接: https://framework.zend.com/manual/2.4/en/modules/zend.view.quick-start.html

另一方面,如果要将对象反序列化为JSON并回显此输出,则应先设置标题。

使用普通的PHP:

header('Content-type: application/json;charset=UTF-8');
echo json_encode($someData);

使用Zend之类的东西:

$this->getResponse()->setHeader('ContentType','application/json;charset=utf-8');
echo $yourJson;