2015-04-02 87 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

相关问题