gpt4 book ai didi

javascript - 尝试使用 Merriam Webster 词典 API 返回的 XML,但请求失败。返回的状态为零。该怎么办?

转载 作者:行者123 更新时间:2023-11-28 06:54:24 24 4
gpt4 key购买 nike

我看到了 Merriam Webster 提供的这个很棒的 AP​​I ( http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm ),它返回一个 XML 文件,其中包含所有详细信息,包括定义和发音。这个 API 需要一个 key ,所以我注册并获得了我的帐户的 key 。我正在使用 Javascript(XHR) 发出请求,但返回的状态为零。然后我用谷歌搜索了错误,它说这可能是因为我的请求来自“file:///”协议(protocol)而不是“http://”,所以我在我的电脑上安装了 LAMP 堆栈,然后将文件托管在我的本地主机上服务器甚至没有运气。另一个线程说我无法发出跨域请求。请你帮帮我。下面是我的 HTML 代码,我可以从中调用 javascript 文件中的函数。

<html>
<head>
<script type="text/javascript" src="context-script.js">
</script>
</head>
<body>
<h1>Merriam Webster</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span><br/>
<b>Sound:</b><span id="sound"></span><br />
</div>
<script>
callOtherDomain();
</script>
</body>
</html>

下面是我的 JAvascript 文件 context-script.js 代码:

function callOtherDomain() 
{
invocation = new XMLHttpRequest();
var url = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/happy?key=8f394b2c-77e8-433d-b599-f3ca87660067';
//url="note.xml";
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
alert("ref");
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
alert("erg");
if (invocation.status == 200)
{
var response = invocation.responseXML;
document.getElementById("to").innerHTML=
response.getElementsByTagName("dt")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
response.getElementsByTagName("dt")[1].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
response.getElementsByTagName("dt")[2].childNodes[0].nodeValue;
}
else
alert(invocation.status);
}
else
dump("currently the application is at" + invocation.readyState);
}

但是当我将 URL 更改为本地存储在本地主机上的“note.xml”时,代码工作得非常好。提前致谢。

最佳答案

虽然这个问题已经有好几年了,但我与 dictionaryapi.com 一起工作过以前的解决方案有两个:

  1. 您在本地服务器上托管的第一步就在( localhost:8000http://127.0.0.1:8000 )。我更喜欢使用 Python SimpleHTTPServer,从您尝试使用您最熟悉/最熟悉的 CLI 工具托管的页面的根目录开始,py -m http.server .
  2. 之后,只需使用 ajax 完成 jQuery 调用即可, get ,或XMLHttpRequest ——随你喜欢。例如:

    $.ajax({
    url: 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/[YourWord]?key=[YourKeyHere],
    method: "GET"
    }).done(function(response){
    console.log(response);
    });

关于javascript - 尝试使用 Merriam Webster 词典 API 返回的 XML,但请求失败。返回的状态为零。该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32677491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com