繁体   English   中英

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

[英]Unable to display Json data using Promise and AJAX requests fetch API

嗨,我在使用Promise和AJAX请求提取API从Web服务检索json数据时遇到问题,代码在

return response.json();

控制台显示此错误

ajaxPromisesTask2.html:47 GET *** / hits.php?artist = dav 401(需要授权)

但是我有很多工作脚本可以连接到相同的Web服务并检索Json数据,但这是我使用内置API的第一个Promise版本。 我究竟做错了什么 ?

链接到Json Web服务: Json文件

仅供参考,我已经尝试过Json.parse(response); 和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/>

默认情况下,如果站点依赖于维护用户会话,则fetch 将不会从服务器发送或接收任何cookie ,从而导致未经身份验证的请求(要发送cookie,必须设置凭据 初始化选项 )。

来源: 使用获取-Web API | 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM