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

时间:2017-08-31 20:30:35

标签: javascript html json ajax

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

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

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

任何指针都会很棒。感谢

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确定

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

1 个答案:

答案 0 :(得分:2)

$.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>