javascript - Ajax 调用 API 来检索 JSON 数据。您如何使用回复

标签 javascript html json ajax

我正在制作一个简单的 Chrome 应用程序,它调用我的 REST API 以检索 JSON 格式的一些基本用户信息。我有下面的内容,在 Chrome 开发人员选项卡预览中显示正在工作、连接和检索我在请求中输入的内容。

我的问题是如何在我的 html 页面上动态显示检索到的内容?

理想情况下,我只显示我的回复中的某些字段。 IE。只是名称、位置、联系电话作为我可以在整个页面中使用的变量。

任何指示都会很棒。谢谢

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Connect to API</title>
  <style>
  img {
    height: 100px;
    float: left;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>

var authorizationToken = "xxxxxxxxxxxxxx";
function myapiRequest(endpoint, method, options) {
  $.ajax($.extend({}, {
    type: method,
    dataType: "json",
     success: function(json) {
              items = json;
            },
    url: "https://api.myapi.com/" + endpoint,
    headers: {
      "Authorization": "Token token=" + authorizationToken,
      "Accept": "application/vnd.myapi+json;version=2"
    }
  },
  options));
}
myapiRequest('/users/0H5G?include%5B%5D=contact_methods&include%5B%5D=teams'); // this will be a variable soon

</script>
</body>
</html>

响应 200 OK

{"user":{"name":"john smith Jsmith","email":"john smith @xxxxxxx.com","time_zone":"Asia/Hong Kong","phone":"0123456",}}

最佳答案

$.ajax({
  type: 'GET',
  url: 'https://jsonplaceholder.typicode.com/posts/1',
  success: function(response) {
  	// if your response is in JSON format, you can access response keys 
   // in the following format (both ways give same result) 
    var title = response.title; // OR var title = response['userId']);
    
    // ...and then append to the DOM (your HTML) by selecting the
    // element you want to append to, and using the append method
    $('div.append-to-me').append(title);
    
  },
  error: function(error) {
  	console.log('not implemented');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append-to-me"></div>

关于javascript - Ajax 调用 API 来检索 JSON 数据。您如何使用回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989630/

相关文章:

javascript - 如何使用 getElementsByClassName 访问特定元素

javascript - Angular Jasmine : View console output from controller?

json - Golang - 将数组/映射转换为 JSON

javascript - XML XPath 和 XSLT 的 JSON 等价物是什么?

javascript - 将 Json Javascript 格式转换为 PHP 可读格式

javascript - 如何获取两个输入事件内两个不同函数内且都在本地范围内的两个变量的总和?

javascript - td 到表格顶部的距离(在可滚动的 div 内)?

javascript - IOS-Chrome : While scrolling screen getting freezed

javascript 将数组的元素映射到 HTML DIV 模板

javascript - html 元素在单选按钮列表中不起作用