2015-04-02 42 views
1

在這裏,我想在json輸出中編碼php返回。我很困惑在那裏實現。所以,我必須做的正確方式。如何使用json_encode作爲基於json的代碼返回

的index.html

$(function(){ 
     $.ajax({ 
      type: 'GET', 
      url: "profile.php", 
      success: function(resp){ 
       var username = JSON.parse(resp).username; 
       var profile = JSON.parse(resp).profile; 
       $('.test').html(username+profile); 

      } 
     }); 
     }); 

profile.php

<?php 
    require_once('class.php'); 
?> 

<?php  
if ($user->is_logged == 1) { 
    $txtuser = ''; 
    if (empty($D->me->firstname)) $txtuser = $D->me->username; 
    else $txtuser = $D->me->firstname; 

    if (empty($D->me->avatar)) $txtavatar = 'default.jpg'; 
    else $txtavatar = $D->me->avatar; 
} 
?> 

<?php 
echo json_encode(array('username' => '{$C->SITE_URL.$D->me->username}', 'profile' => '{$txtuser}')); 
?> 
+0

會''C-> SITE_URL。$ D-> me-> username'和'$ txtuser'總是一個字符串? – CodeGodie 2015-04-02 18:17:14

+1

刪除全部無用 Zl3n 2015-04-02 18:23:12

+0

輸出當我使用PHP作爲返回數據是用戶名:「http:// localhost/data/johnmike」,個人資料:「約翰」 – smile 2015-04-02 18:24:58

回答

0

要把它清理乾淨這樣,讓我知道,如果你仍然有問題:

<?php 
    require_once('class.php'); 

    if ($user->is_logged == 1) { 
    $txtuser = ''; 
    if (empty($D->me->firstname)) $txtuser = $D->me->username; 
    else $txtuser = $D->me->firstname; 

    if (empty($D->me->avatar)) $txtavatar = 'default.jpg'; 
    else $txtavatar = $D->me->avatar; 
    } 

    $arr = array(
    "username" => $C->SITE_URL . $D->me->username, 
    "profile" => $txtuser 
); 

    echo json_encode($arr); 
?> 

在阿賈克斯響應使用console.log(resp)查看控制檯中的任何錯誤。

+0

噢,謝謝@CodeGodie,我已經嘗試過了,但遇到錯誤「可捕獲的致命錯誤:類stdClass的對象無法轉換爲字符串」 – smile 2015-04-02 18:37:35

+0

但在我的代碼的ajax函數中是正確的響應方式? – smile 2015-04-02 18:40:23

+0

好吧現在就試試,讓我知道你得到了什麼 – CodeGodie 2015-04-02 19:04:31

0

dataType選項設置爲json,這樣你就可以告訴jQuery服務器的數據是JSON格式,而jQuery會嘗試將JSON字符串轉換爲對象。這是不需要手動做JSON.parse()

$.ajax({ 
    type: 'GET', 
    url: "profile.php", 
    dataType: 'json',   
    success: function(resp){   
     console.log(resp); 
    } 
}); 

使用console.log()檢查結果(MozillaChrome)。

另一件事是,你應該刪除引號,只是連接字符串與點(PHP String Operators)。此外,json_encode()之前和之後不應該有任何輸出,因爲它會打破json字符串,su只使用die()

die(json_encode(array('username' => $C->SITE_URL . $D->me->username, 'profile' => $txtuser))); 
+0

謝謝@ Danijel,所以如何使用json.parse()來獲取用戶名和配置文件? – smile 2015-04-02 19:18:47

+0

噢,我明白了,只是resp.username,resp.profile – smile 2015-04-02 19:23:32

+0

@CodeGodie,感謝downvote太多了,我希望你現在感覺更好。 – Danijel 2015-04-02 21:31:36