【问题标题】:Can't display returned JSON when using Jquery使用 Jquery 时无法显示返回的 JSON
【发布时间】:2012-02-08 17:11:39
【问题描述】:

我正在尝试使用 jquery 检索在我的 php 脚本中生成的以下 json。但是,我无法显示它。如果我提醒它,它只会显示“未定义”。使用 $('#demo').html(data.htmlOutput) 来显示 html 也无济于事。请有人指出我做错了什么?

$arr = array('htmlOutput' => '<b>hello</b>', 'no_rows' => 'balh');
echo json_encode($arr);

$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
        alert (data.htmlOutput);
        alert (data.no_rows)
        $('#demo').html(data.htmlOutput);
}

我可以在 FB 控制台中看到 json 响应,但是它仍然什么都不做。

【问题讨论】:

  • 脚本如何知道将其解析为 JSON?
  • @BarryChapman。应该知道的,看我下面的回答。
  • @gdoron - 我正在应用“重定向”。我希望他可能意识到他并没有告诉脚本它需要 json 并且可以找到答案:)
  • @BarryChapman。 jQuery 团队在他们的文档中说他们默认使用 Intelligent Guess...所以它本来可以工作...

标签: php jquery json post


【解决方案1】:

告诉 jquery 你期待 json,它是最后一个参数:

$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
        alert (data.htmlOutput);
        alert (data.no_rows)
        $('#demo').html(data.htmlOutput);
}, "json");

【讨论】:

    【解决方案2】:

    你已经告诉 jquery 你期待 json 对象,使用 dataType 如下:

    .post('get-offers.php', $("#offerForm").serialize(), function(data) {
            alert (data.htmlOutput);
            alert (data.no_rows)
            $('#demo').html(data.htmlOutput);
    },'json'); //<====
    

    dataType:服务器预期的数据类型。

    docs

    我认为 jquery 将能够猜测它是一个 json 对象,因为在他们的文档中写道:

    默认:智能猜测(xml、json、脚本、文本、html)。

    嗯,我猜那个猜测不是那么聪明……=)

    【讨论】:

      【解决方案3】:

      两种选择:

      首先,将 'json' 设置为 $.post 的最后一个参数,告诉它它正在等待 JSON 响应。

      其次,在您的第一个警报之前,添加以下内容:

      var obj = jQuery.parseJSON(data);
      

      然后alert(obj.htmlOutput);

      看看是否适合你

      【讨论】:

        猜你喜欢
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 2013-10-15
        • 1970-01-01
        • 2011-08-15
        • 2015-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多