javascript - 无法使用 Promise 和 AJAX 请求获取 API 显示 Json 数据

标签 javascript ajax api promise

您好,我在使用 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/

相关文章:

javascript - 在 reducer 中向 redux store 添加功能是一种反模式?

javascript - JSON 未定义或 null

c# - Facebook API,导出群组墙条目

http - 将接口(interface)写入 Web 服务 API

javascript - 使用javascript反向数组遍历

javascript - 如何在fabricjs中停止或暂停动画

javascript - 响应式框架中的滑动窗口/缓冲区

javascript - 如何显示 jQuery 自动完成响应并选择它?

javascript - 在提交到 PHP 上传之前在客户端调整图像大小

javascript - 使用外部 API 和 Salesforce 自动完成字段