Py学习  »  Jquery

使用jQuery和Ajax(返回的对象对象)加载API时,无法确定如何让它在控制台或任何地方显示JSON数据

sandorfalot • 3 年前 • 663 次点击  

我用下面的代码调用一个API,如果我得到的只是对象对象。我试过一些不同的方法,但没有成功。我正在获取jquery-3.4.1.min.js:2xhr已完成加载:在控制台中获取“url.to.api”。这是我的密码。

<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript" src="./jquery-3.4.1.min.js"></script>

<title></title>
</head>
<body>
<script>
$.ajax({
 type: "GET",
url: "to API", // note, this doesn't end in JSON, but if I type the URL into my browser, I can view the JSON data

// Request headers
beforeSend: function(xhrObj) {
    xhrObj.setRequestHeader("Cache-Control", "no-cache");
    xhrObj.setRequestHeader("Subscription-Key", my key");
    },
})
.done(function (data) {
alert(data); // I changed this from a 'success' pop up to tell me it was working, but I can't display the data anywhere, so I tried in the box, and got object object
})
   .fail(function () {
  alert("error");
});
     </script>
</body>
</html>

我是API的新手,这方面根本没有文档。谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57121
 
663 次点击  
文章 [ 1 ]  |  最新文章 3 年前
willi123yao
Reply   •   1 楼
willi123yao    3 年前

API url不需要以JSON结尾。如果您通过浏览器查看API响应,并且它确实是JSON语法,那么API很可能会以JSON格式输出结果。

在这种情况下,ajax请求将自动解析从API调用到javascript对象的响应,这就是为什么它将显示 [object Object] alert(data) .

要将javascript对象的内容打印为字符串,只需在使用 JSON.stringify() 语法如下:

alert(JSON.stringify(data)); // I changed this from a 'success' pop up to tell me it was working, but I can't display the data anywhere, so I tried in the box, and got object object