【问题标题】:JSON encoding with Services_JSON and json_encode in PHP returning empty object with jQuery ajax call在 PHP 中使用 Services_JSON 和 json_encode 进行 JSON 编码,使用 jQuery ajax 调用返回空对象
【发布时间】:2013-04-05 09:33:06
【问题描述】:
            $.ajax({
                url: '/ajax/get_rule.php',
                dataType: 'json',
                data: {                 
                    feature : feature,
                    ajax : 1
                },
                success: function(resp) {
                    console.log('in here');
                    console.log('response: ' + resp);

                },
                error : function() {
                    console.log('there was an error...');
                }
            }); 

我正在使用 PHP PEAR Services_JSON 类将我的数组编码为 JSON 字符串,然后在响应中回显,如下所示:

echo Registry('json')->encode(array('ajax' => 1, 'feature' => 'rfc1872'));
exit;

在上面的例子中,Registry('json') 是一个Services_JSON 对象。

我也试过PHP内置函数json_encode

echo json_encode(array('ajax' => 1, 'feature' => 'rfc1872'));
exit;       

这些都不起作用,虽然我没有陷入上述 jQuery ajax 调用中的错误回调,但我在 Firebug 中得到了一个带有空对象的 response: [object Object] 响应值。

为什么我不会收到对带有 JSON 编码字符串的 jQuery 代码的响应?

【问题讨论】:

  • 你怎么知道它是空的?我没有看到您将其记录到控制台。 console.log('response: ' + resp); 会先将对象转换为字符串,对象的默认字符串表示为"[object Object]",不管它是否有属性。 console.log(resp); 向您展示了什么?如果您没有收到 JSON 作为响应,我相信甚至不会执行成功回调。
  • 天哪,原来是这样。按照您的建议,我将console.log('response: ' + resp); 更改为console.log(resp);,并且对象正确通过。非常感谢,您能否提交作为答案,我会很乐意接受。感谢您指出这一点。

标签: php javascript jquery json


【解决方案1】:

正如 Felix King 在上面的评论中所提供的,这实际上是由于将resp 转换为具有以下内容的字符串:

console.log('response: ' + resp)

改为:

console.log(resp);

解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2012-12-05
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多