您好,我在使用 Promise 和 AJAX 请求获取 API 从 Web 服务检索 json 数据时遇到问题,代码失败
return response.json();
控制台显示此错误
ajaxPromisesTask2.html:47 GET ***/hits.php?artist=dav 401 (Authorization Required)
但我有许多工作脚本连接到相同的 Web 服务并检索 Json 数据,但这是我使用内置 API 的第一个 Promise 版本。我做错了什么?
链接到 Json Web 服务: Json file
FYI, I have tried Json.parse(response); and JSON.stringify(response);
<script type='text/javascript'>
function ajaxrequest()
{
var a = document.getElementById("artist").value;
fetch('/hits.php?artist=' + a).then(ajaxresponse).
then(showJSONResults).catch(ajaxerror);
}
function ajaxresponse(response)
{
return response.json();
}
function ajaxerror(code)
{
alert('error; ' + code);
}
function showJSONResults(jsonData)
{
var output = "<table style='width:100%'> <tr> <th>Title</th> <th>Artist</th> <th>Chart position</th> </tr>";
for(var i=0; i < jsonData.length; i++)
{
output = output + ' <tr> <td>' + jsonData[i].title + '</td><td>' + jsonData[i].artist + '</td><td>' + jsonData[i].chart + '</td></tr>';
}
output = output + "</table>";
document.getElementById("response").innerHTML = output;
}
</script>
</head>
<body>
<div id="info">
<input id="artist" /> <br/>
<input type="button" value="Search" onclick="ajaxrequest()" />
<div/>
<div id="response"><div/>
最佳答案
<小时/>By default,
fetch
won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).Source: Using Fetch - Web APIs | MDN
您必须提供一个带有 credentials
属性的对象,该属性的值设置为same-origin
才能提交授权 cookie。
function ajaxrequest()
{
var a = document.getElementById("artist").value;
fetch('/hits.php?artist=' + a, { credentials: 'same-origin' })
.then(ajaxresponse)
.then(showJSONResults)
.catch(ajaxerror);
}
关于javascript - 无法使用 Promise 和 AJAX 请求获取 API 显示 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47556868/