2015-09-23 23 views
2

我使用的是詞庫API,JavaScript警告不工作時,API的HTTP請求有JSON錯誤(沒有找到)

http://thesaurus.altervista.org

得到同義詞打印頁面。在這個演示版本,

http://plnkr.co/edit/6pNYlXcgiwxHz00AY5CT?p=preview

,當你鍵入 '和平',否則,在控制檯它的工作原理,如果我們按照鏈接,我們看到了一個GET錯誤:

{"error":"the key test_only is restricted, please use your own key!"} 

(編輯:澄清:演示模式不是問題,我想提醒一下)。對於錯誤,我希望瀏覽器提醒「哎呀,找不到詞,請選擇另一個詞。」

這是從演示的js代碼:

//function activated on user input 
    function myFunc(){ 
     var userInput = document.getElementById('userInput'); 
     var result = userInput.value; 
     var s = document.createElement("script"); 

     //This demo works with the keyword 'peace' only. So searching for e.g. 'hat' will cause an error. 
     s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process"; // NOTE: replace test_only with your own KEY 
     document.getElementsByTagName("head")[0].appendChild(s); 

     window.process = function (result) { 
      //my attempt at throwing an error 
      if(result.error){alert("Oops, word not found. Please choose another word.");} 
      //normal processing.. 
      output = ""; 
      for (key in result.response) { 
      list = result.response[key].list; 
      output += list.synonyms+"<br>"; 
     } 
      if (output) 
      document.getElementById("synonyms").innerHTML = output; 
     } 
    } 

我做了一些研究,發現這個答案(這是jQuery的,但我的不是,但它可能是相關的?):

https://stackoverflow.com/a/2568788

任何幫助非常感謝,謝謝。

回答

1

這是因爲您需要生成自己的密鑰。您使用的密鑰只是一個示例密鑰。

Right there

然後你會改變test_only是由生成的密鑰的網址。

無論如何,這可能意味着服務不是免費使用的,所以如果您計劃在商業上使用它,請小心並閱讀許可證。

+0

嗨Secular Kid,謝謝你的回答。請參閱編輯。 – MediaMaker

0

您需要用您的API密鑰替換測試API密鑰。

您可以將http://thesaurus.altervista.org/mykey和註冊或登錄得到您的API密鑰

你甚至可以在你的代碼中的註釋,告訴你這樣做:如果你的API

s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=test_only&callback=process"; 
// NOTE: replace test_only with your own KEY 

所以鍵123456789,你的URL將如下所示: s.src = "http://thesaurus.altervista.org/service.php?word=" + result + "&language=en_US&output=json&key=123456789&callback=process";

+0

嗨mittmemo,謝謝你的回答。請參閱編輯。 – MediaMaker

相關問題