javascript - JSON 响应不是来自 php 的对象

标签 javascript php ajax json

我使用 php 代理来绕过跨域 ajax 问题

我的PHP:

return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content
    );

所以现在我的 $response['content'] 保存我的内容,但我也想要我的标题。

如果我:

echo $response['content'];

然后我得到的回复如下: enter image description here

这就是我需要的!但我也想在回显中包含 $response[header] 。 但如果我:

echo $response;

我得到: enter image description here

如何在 json 响应中获取两者,以便我可以在我的 javascript 代码中使用它? 为什么它只返回明文“Array”

如果我使用 json_encode 它的格式不正确,就像我的第一个示例一样。

enter image description here

它丢失了所有格式..?

最佳答案

您必须使用 json_decode() 解析响应数据 $content

$data = array(
    'status' => 'ok',
    'header' => $header,
    'content' => json_decode($content)
);

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

或者您可以直接返回 JSON,而不进行解析

header('Content-type: application/json');
echo '{"status":"ok", "header":"' . $header . '", "content":"' . $content . '"}';

关于javascript - JSON 响应不是来自 php 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495351/

相关文章:

javascript - 传递值将 Ajax 抛出到一个 php 文件

javascript - 如何按字母顺序对页面上具有 optgroup 的所有选择框进行排序,而不将选项移出各自的组?

php - 如何从 PHP 压缩或转换为低质量的 Mp3 文件

php - 使用 JQuery 和 CodeIgniter 将注释安全地写入数据库?

javascript - 从 app.get 回调调用的模块中的主文件访问变量

javascript - 从 jquery .data 对象检索一个属性

php - 如何在我的 FormRequest 中添加自定义验证器?

ajax - 通过ajax请求将字符串发送到php gd

jquery - PageMethod 与 ajax 异步调用

php - 拉取php数据,使用split分隔字符串中的逗号,将数据发布到div中使用ajax每3秒刷新一次