[英]Ajax Request to AWS API Gateway can not parse json response
我在這里測試代碼: 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
您可以直接轉到該URL,然后發現AWS-API-Gateway
的響應很簡單:
{
"cc":"dd",
"name":"ee"
}
我能夠使用上面的javascript解析其他來源的其他json
響應。 但是我正在努力嘗試解析來自AWS-API-Gateway
的上述響應。 如果您取消注釋var myURL
的第二行,則會看到該代碼確實適用於其他URL。
==========
針對現有答案:
json
和jsonp
。 兩者都適用於其他URL(包括我評論過的URL)。 但兩者均不適用於AWS Gateway API。 這是數據類型。 您正在告訴jQuery期待jsonp回調。 您正在尋找的是dataType:“ json”。
更新
我剛剛測試了您的代碼。 問題是您在pettest / test資源中沒有定義OPTIONS方法。 使用API Gateway控制台,打開測試資源(假設pettest是階段,而test是資源),然后使用“操作”下拉按鈕來啟用CORS。 這將自動創建OPTIONS方法並在GET方法中設置所需的標頭。
為我使用了您的API。 可能沒關系,但是我沒有使用'resp'作為變量標簽,而是使用了'data'。
另外,調用命名函數而不是內聯嵌入函數
function processJSON(data) {
alert(data.name);
}
dataType: "json",
contentType: 'application/json',
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.