2015-08-18 37 views
0

我在Zend的動作代碼如下:獲取JSON錯誤1

$this->getResponse() 
      ->setHeader('Content-Type', 'application/json'); 
$result = array("status" => true, "result" => $output); 
     $json = json_encode($result); 
echo $json; 

而且我的角度控制器如下:

app.controller("statController", function($scope, $http){ 
     $http.get("mydomain/controller/action/") 
     .success(function(response) { 
     console.log(response) 
     }).error(function(response) { 
       alert(response) 
      console.log('Error : ' + response); 
     }); 
}); 

當我打電話的網址從瀏覽器中檢查並在Network選項卡中檢查結果是否在json中。 但是,當我從我的角度電話檢查它,結果有此錯誤:

SyntaxError: JSON.parse: unexpected end of data 

此外,我打電話(zend的控制器和動作)的網址不在同一個域中我angular.js代碼。我使用Zend Framework 1.

UPDATE 我找到了這個prblem。我試圖從不同的域名訪問,所以我只需要添加

$this->getResponse()->setHeader('Access-Control-Allow-Origin', '*'); 

對我的行爲。

+0

嘗試:678941 $ this-> getHelper('Layout') - > disableLayout(); $ this-> getHelper('ViewRenderer') - > setNoRender(); ('Content-Type','application/json; charset = UTF-8'); $ this-> getResponse() - > setHeader $ result = array(「status」=> true,「result」=> $ output); $ json = json_encode($ result,JSON_UNESCAPED_UNICODE); echo $ json;出口;欲瞭解更多詳情: - http://se2.php.net/json_encode –

回答

0

試試下面的代碼在你的動作,

public function yourAction() 
{ 
    // Disable the layout and view for the action 
    $this->_helper->layout()->disableLayout(); 
    $this->_helper->viewRenderer->setNoRender(); 

    // Set the header as JSON 
    header("Content-Type:application/json"); 

    // Your code starts here 
    // ......................... 
    $result = array("status" => true, "result" => $output); 
    $json = json_encode($result); 

    echo Zend_Json::encode($json); 
} 

注:代碼沒有進行測試。嘗試一次,可能是你的佈局或其他問題。

+0

謝謝。對於答覆,這些都沒有幫助。我通過添加'$ this-> getResponse() - > setHeader('Access-Control-Allow-Origin','*')找到了修復程序;''到我的控制器,因爲我試圖從不同的域訪問。 – DrStein