将API响应数据保存为HTML元素

时间:2017-07-28 18:14:56

标签: javascript html json aws-lambda aws-api-gateway

我有一个内置JavaScript的html文件。我还有一个URL,打开时只是一个页面,其中包含我使用AWS API Gateway制作lambda API时收到的AWS lambda API调用的数据。当页面加载类似于

的数据时,页面看起来像一个完全空白的页面
[
{"user": "bob", "groups": ["bobsGroup"], "policies": ["bobsPolicy", "anotherPolicy"["Policy3"]]},
{"user": "sal", "groups": ["salsGroup"], "policies": ["salssPolicy", "anotherPolicy"["Policy3"]]}
]

我的问题是我想从API响应中获取数据并将其保存到HTML段落元素中。我不认为我现在正在使用正确的逻辑或以不正确的方式执行它,尝试在我的脚本标记内运行以下内容,

var myjson;
$.getJSON("https://myapi.execute-api.us-east-2.amazonaws.com/myapi//myapiresource", function(json){myjson = json;});
document.getElementById("demo").innerHTML = myjson

其中demo只是我的HTML

中的段落标记

完整的代码段是,

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">


  </head>
  <body>


  <div id = "demo"></div>




    <script>

        var myjson;
$.getJSON("https://myapi.execute-api.us-east-2.amazonaws.com/myapi//myapiresource", function(json){ 
  document.getElementById("demo").innerHTML = json;
});


    </script>


  </body>
</html>

1 个答案:

答案 0 :(得分:0)

在ajax成功回调中移动var myjson; $.getJSON("https://myapi.execute-api.us-east-2.amazonaws.com/myapi//myapiresource", function(json){ myjson = json; document.getElementById("demo").innerHTML = myjson; }); ...

$.getJSON("https://myapi.execute-api.us-east-2.amazonaws.com/myapi//myapiresource", function(json){ 
  document.getElementById("demo").innerHTML = json;
});

代码清理版

Private Declare PtrSafe Function SafeArrayRedim Lib "OleAut32" ( _
  ByVal arr As LongPtr, ByRef dims As Any) As Long


Public Sub RedimDouble(arr() As Double, ByVal count As Long)
  If count Then
    ReDim Preserve arr(0 To count - 1)
  Else
    ReDim arr(0 To 0)
    SafeArrayRedim Not Not arr, 0@
  End If
End Sub


Public Sub Usage()

  Dim arr_double() As Double
  RedimDouble arr_double, 0    ' Double(0 to -1) '

End Sub