2012-08-23 47 views
1

返回數組對象然後將其顯示給用戶時出現問題,請查看演示代碼。一個基本的片段,但它有相同的想法,我只是不能在這裏發佈很長的代碼。返回數組對象時出錯

Class foobar{ 
    public function foo() 
    { 
    return array('bar' => 'value'); 
    } 
} 

這PHP代碼被用來通過另一個類

Class foobar_fetcher{ 
    public function getFoo() 
    { 
    $fb = new foobar(); 
    $result = $fb->foo(); 
    return $result; 
    } 
} 

foobar_fetcher由主劊子手文件(ajaxdispatcher.php)再次調用 - 用JSON報頭。

if(isset($_POST['fetch'])){ 
    $httpresponse = new stdClass(); 
    $fb_fetch = new foobar_fetcher(); 
    $httpresponse->data = $fb_fetch->getFoo(); 
} 

echo json_encode($httpresponse); 

最後,這個ajaxdispatcher被jquery ajax調用。

$.ajax({ 
    url: 'ajaxdispatcher.php', 
    type: 'post', 
    data: {fetch:'fetch'}, 
    success: function(data){ 
     if(data) console.log(data); 
    } 
}); 

現在,當我嘗試打印數據時,它沒有來自服務器的響應。 但是,當我將foobar類下的foo()的返回值更改爲一個整數或字符串。事情會正常工作。

+1

廣東話重現,似乎工作,這是實際的代碼?或僞:http://codepad.org/yAv7aX2J –

回答

2

您應該嘗試更改您的ajaxdispatcher以接受GET請求,並從瀏覽器中導航以查看返回的內容。

if(isset($_GET['fetch'])){ 
    $httpresponse = new stdClass(); 
    $fb_fetch = new foobar_fetcher(); 
    $httpresponse->data = $fb_fetch->getFoo(); 
} 

echo json_encode($httpresponse); 

導航到/ajaxdispatcher.php?fetch=fetch

+0

我已經試過這種方法。它工作正常。但是當它顯示給ajax時,它沒有任何反應。 –

+1

你使用什麼瀏覽器?如果您使用的是Chrome,則可以檢查請求和響應,並查看出錯的位置。 – mcottingham

0

有些事情,我會那樣做可能會提高你成功的機會

  1. 設置適當的HTTP標頭和exit發送後您的JSON代碼

    header('Content-type: application/json'); 
    echo json_encode($httpresponse); 
    exit; 
    

    還請確保您沒有發送任何數據到此之前的輸出緩衝區。

  2. 告訴jQuery的數據類型期望

    $.ajax({ 
        dataType: 'json', 
        // and the rest 
    
  3. 添加error回調

    $.ajax({ 
        // snip 
        error: function(jqXHR, textStatus, errorThrown) { 
         console.log(jqXHR, textStatus, errorThrown); 
        } 
    }); 
    
+0

錯誤捕獲器可以幫助我。想辦法。謝謝一堆 –

+0

@KennethPalaganas那麼問題是什麼? – Phil