2017-02-11 20 views
1

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

这个警告只发生在表为空时,但是这个问题只是在sql查询中使用group关键字时才会出现,如果我不使用group关键字,那么它只给出表中的一条记录,但表中有更多记录也。当我使用以下查询时,输出变为显示所有记录,只有表中有数据,如果不显示数据表示警告。 // sql查询(型号/表/ 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'))); 

} 

下面的查询将只显示一个记录,如果表中有多个记录。如果表格是空的,那么我会来“表格消息中没有数据可用”。

// sql查询(型号/表/ 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")); 

回答

0

正确的方法是将“ViewJsonStrategy”添加到您的模块的配置,并将您的视图模型为“终端”。

类似的东西:

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; 
相关问题