【问题标题】:$.ajax not able to receive JSON HTTP Response$.ajax 无法接收 JSON HTTP 响应
【发布时间】:2013-06-02 05:01:09
【问题描述】:

我是 JavaScript、JQuery 和 Ajax 编码的新手。 我正在使用 JQuery $.ajax 方法来调用异步 REST 调用。 不知何故,我无法接收 HTTP 响应 JSON 数据。

我可以看到以下警报结果。 alert(data) 方法的结果是 [Object Object] alert(data.toSource()) 方法结果为 ({"key1","value1"}) alert($.parseJSON(data)) 方法结果什么都没有

我已经在 Firefox 和 chrome 浏览器中测试了以下代码。

<html>
<head>
<title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
</head>
<body>
    <form id="foo">
        <label for="bar">A bar</label>
        <input id="bar" name="bar" type="text" value="" />
        <input type="submit" value="Send" />
    </form>
    <!-- the result of the search will be rendered inside this div -->
    <div id="result"></div>
    <script>
        $("#foo").submit(function(event) {
            event.preventDefault();
            $("#result").html('');
            var values = $(this).serialize();
            $.ajax({
                url: "resources/helloWorld",
                type: "GET",
                dataType: 'json',
                success: function(data){
                    alert(data);
                    alert(data.toSource());
                    var r = $.parseJSON(data);
                    alert(r);
                    $("#result").html(data);
                },
                error:function(){
                    $("#result").html('there is error while submit');
                }  
            });
        });
    </script>
</body>

【问题讨论】:

  • 您返回的是有效的 JSON 吗?
  • 我的 json 响应是 {"key1":"value1"}
  • 你能发布json文件吗?这很容易分析。
  • 一切都很好。使用console.log() 而不是alert(),您会在控制台中看到正确的数据。

标签: javascript ajax jquery


【解决方案1】:

来自您的帖子:

alert(data) -> [Object Object]

对,alert() 使用参数的字符串表示,data 是一个对象。

alert(data.toSource()) -> ({"key1","value1"})

对,toSource() 是一种 Gecko 方法,其作用类似于 JSON.stringify

alert($.parseJSON(data)) method result is nothing

对,你正在尝试解析一个对象。


你想要做的可能是这样的:

success: function(data){
  $("#result").html(data.key1);
}

【讨论】:

  • 感谢您帮助我。是的,它对我有用。我想接收整个 JSON 响应并解析这个 JSON。因为我的 JSON 非常复杂。我不能使用 $.parseJSON 方法来解析我的 HTTP 响应吗?
  • @RaviHingarajiya 你的 json 已经被解析了。在success 函数中运行console.log(data) 以检查它。
猜你喜欢
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 2018-01-23
  • 2016-10-25
相关资源
最近更新 更多