尝试使用韦氏词典API返回的XML,但请求失败.返回状态为0.该怎么做

Trying to use XML returned by merriam webster dictionary API but request getting failed. Status returned is zero. What to do?

本文关键字:返回 失败 状态 请求 XML API      更新时间:2023-09-26

我看到了merriam webster的这个很棒的API (http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm),它返回一个包含所有细节的XML文件,包括定义和发音。这个API需要一个密钥,所以我注册并得到了一个密钥为我的帐户。我正在使用Javascript(XHR)发出请求,但返回的状态为零。然后我用谷歌搜索了错误,它说这可能是因为我的请求是从"file:///"协议而不是"http://",所以我在我的PC上安装了LAMP堆栈,然后在我的本地主机服务器上托管了文件,甚至没有运气。另一个线程说,我不能使跨域请求。你能帮帮我吗?下面是我在javascript文件中调用函数的HTML代码。

<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. 之后,只需使用ajaxgetXMLHttpRequest(您喜欢哪个)完成一个jQuery调用。例如:

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