使用JavaScript获取JSON响应并在网页上显示,测试JavaScript

all*_*tar 5 javascript ajax jquery json

我正在尝试使用以下功能创建一个JS应用程序:一个获取JSON文档并显示该文本的按钮.我正在阅读Elasticsearch教程,我提供的网址确实存在有效的JSON:

{"_index":"planet","_type":"hacker","_id":"xfSJlRT7RtWwdQDPwkIMWg","_version":1,"exists":true, "_source" : {"handle":"mark","hobbies":["rollerblading","hacking","coding"]}}
Run Code Online (Sandbox Code Playgroud)

使用下面的代码时......我收到了警报

[object Object]
Run Code Online (Sandbox Code Playgroud)

而不是具有完整JSON的警报.我打算采取下一步实际选择部分JSON的步骤,但我想至少先查看完整的文档......

有任何想法吗?先感谢您!

<!DOCTYPE html>
<html lang="en">
<head><title>Demo</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /></head>

<body>
  <input id="testbutton" type="button" value="Test" />
  <p id="results">results appended here: </p>

<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#testbutton").click(function() {
        $.ajax({
            url: 'http://localhost:9200/planet/hacker/xfSJlRT7RtWwdQDPwkIMWg',
            dataType: 'json',
            success: function(data) {
                $("#results").append('all good');
                alert(data);
            },
             error: function() {
                $("#results").append("error");
                alert('error');
            }
        });
    });
});
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

kul*_*_mi 17

使用 alert(JSON.stringify(data));