对AWS API Gateway的Ajax请求无法解析json响应

时间:2016-08-09 04:08:41

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

我在这里测试代码: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get

以下是代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var processJSON =  function(data, textStatus, xhr) {
       alert(xhr.status);
    }
// for whatever reason, the following URL is not working any more, so you won't be able to test it anymore.
  var myURL='https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223';
//  var myURL="https://jsonplaceholder.typicode.com/users"

    $("button").click(function(){
        $.ajax({
          url: myURL,
          dataType: "json",
          contentType: 'application/json',
          success: processJSON
        });


    });
});
</script>
</head>
<body>

<button>Send Request</button>

</body>
</html>

如代码所示,我试图解析来自此URL的响应: https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223

您可以直接转到该网址,并发现AWS-API-Gateway的响应只是:

{
 "cc":"dd",
 "name":"ee"
}

我能够使用上面的javascript解析来自其他来源的其他json响应。但我正在试着解析AWS-API-Gateway的上述反应。 如果您取消注释var myURL的第二行,您会看到该代码确实适用于其他网址。

==========

回应现有答案:

  • 我尝试了jsonjsonp。两者都适用于其他URL(包括我评论的那个)。但它们都不适用于AWS Gateway API。
  • 我还更新了代码以使用命名函数。但同样,它适用于其他URL,但不适用于AWS URL。
  • 我在Firefox和Safari上测试过它。

2 个答案:

答案 0 :(得分:2)

这是数据类型。你告诉jQuery期待jsonp回调。你要找的是dataType:“json”。

更新

我刚刚测试了你的代码。问题是您没有在pettest / test资源中定义OPTIONS方法。使用API​​网关控制台,打开测试资源(假设pettest是阶段,测试是资源),然后使用“操作”下拉按钮启用CORS。这将自动创建OPTIONS方法并在GET方法中设置所需的标题。

答案 1 :(得分:0)

使用您的API为我工作。可能没关系,但我没有使用'resp'作为变量标签,而是使用'数据'。

此外,调用命名函数而不是嵌入函数内联

    function processJSON(data) {
      alert(data.name);
    }

          dataType: "json",
          contentType: 'application/json',