Php 如何使用json_encode作为基于json的代码返回

Php 如何使用json_encode作为基于json的代码返回,php,jquery,ajax,json,Php,Jquery,Ajax,Json,在这里,我想在json输出中对php返回进行编码。在那里实现我太困惑了。那么,我该怎么做才是正确的 index.html $(function(){ $.ajax({ type: 'GET', url: "profile.php", success: function(resp){ var username = JSON.parse(resp).username;

在这里,我想在json输出中对php返回进行编码。在那里实现我太困惑了。那么,我该怎么做才是正确的

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}' ));
?>

以这种方式清理,如果您仍然有问题,请告诉我:

<?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);
?>

在Ajax响应中,使用
console.log(resp)
查看控制台中的任何错误。

将选项设置为
json
,这样您就可以告诉jQuery预期来自服务器的数据是json格式的,jQuery将尝试将json字符串转换为对象。无需使用
JSON.parse()
手动执行此操作

使用
console.log()
检查结果(,)

另一件事是,您应该删除引号,只需将字符串与点(PHP)连接起来。另外,在
json_encode()
之前和之后都不应该有任何输出,因为它会破坏json字符串,所以只需使用


$C->SITE\u URL.$D->me->username
$txtser
是否总是一个字符串?当我使用php时,删除所有无用的输出,因为返回数据是username:,profile:“John”使用双引号,您不必费心将变量封装在
{}
中,因此它们都是字符串。如果它们都是字符串,并且您使用的是
json\u encode
,则不会出现错误。你得到了什么错误?哦,谢谢@CodeGodie,我已经尝试过了,但是得到了错误“可捕获的致命错误:类stdClass的对象无法转换为字符串”,但是,在ajax中,我的代码的函数是正确的响应方式吗?是的。它工作得很好,非常感谢@CodeGodie:D@den令人惊叹的很高兴我能提供帮助。我给你下一票,因为你没有提供任何解释答案的努力,这是问题中无效代码的纯拷贝粘贴,带有卷曲语法问题中的字符串连接。谢谢@Danijel,那么如何使用json.parse()?@CodeGodie获得用户名和配置文件,也谢谢下一票,我希望你现在感觉好些了。
$.ajax({
    type: 'GET',
    url: "profile.php",
    dataType: 'json',           
    success: function( resp ){          
        console.log( resp );
    }
});
die( json_encode( array( 'username' => $C->SITE_URL . $D->me->username, 'profile' => $txtuser ) ) );