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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17913241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:11:54  来源:igfitidea点击:

Using JavaScript to get JSON response and display on the webpage, testing JavaScript

javascriptjqueryajaxjson

提问by allstar

I'm trying to create a JS app with the following functionality: A button that gets a JSON document and displays that text. I'm going through an Elasticsearch tutorial, and there is indeed valid JSON at the url I provide:

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

{"_index":"planet","_type":"hacker","_id":"xfSJlRT7RtWwdQDPwkIMWg","_version":1,"exists":true, "_source" : {"handle":"mark","hobbies":["rollerblading","hacking","coding"]}}

When using the code below...I get an alert of

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

[object Object]

instead of an alert with the full JSON. I'm planning to take the steps next of actually selecting part of the JSON, but I'd like to at least see the full document first...

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

Any ideas? Thank you in advance!

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

<!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>

回答by kul_mi

Use alert(JSON.stringify(data));

alert(JSON.stringify(data));

回答by Matt

jQuery tries to "best guess" the data format it receives, and parse it for you.

jQuery 尝试“最佳猜测”它接收的数据格式,并为您解析它。

That's exactly what you're seeing. jQuery has already parsed the JSON into an object for you. To see the JSON representation, you can stringify the data again;

这正是你所看到的。jQuery 已经为您将 JSON 解析为一个对象。要查看 JSON 表示,您可以再次对数据进行字符串化;

alert(JSON.stringify(data));

... or, you can tell jQuery not to parse the response in the first place, passing dataType: "string"as one of the options. datawill then be the JSON representation, and you'll have to JSON.parse(data)to turn it into an object.

...或者,您可以告诉 jQuery 首先不要解析响应,将其dataType: "string"作为选项之一传递。data然后将是 JSON 表示,您必须JSON.parse(data)将其转换为对象。

回答by shyam

You are getting the JSON converted to a javascript object from which you can access the individual properties using the .operator like

您正在将 JSON 转换为 javascript 对象,您可以从中使用.运算符访问各个属性,例如

alert(data._type);

回答by Leonard Pauli

Simple!

简单的!

alert()calls .toString()on the object which returns "[object Object]".

alert()调用.toString()返回“[object Object]”的对象。

Use console.log(data), right-click and goto the console (or hit F12).

使用console.log(data),右键单击并转到控制台(或按 F12)。

Or just do as the others: alert(JSON.stringify(data));

或者只是做像其他:alert(JSON.stringify(data));