2017-05-28 71 views
0

我想獲得一個API工作,它從這個網站獲取瑣事問題:https://opentdb.com/api_config.php。這裏是我的代碼:如何設置此API獲取請求?

if (auth && data.user == user && match('trivia', data.msg)) { 
    $("button").click(function() { 
    $.get("https://opentdb.com/api.php?amount=10&token=d6685dc31db69e33eeb1c3828ffa2c587d5ec43dc6dd995ebefe85681796d149", function(data, status) { 
     sock.chat("Data: " + data + "\nStatus: " + status); 
    }); 
    }); 
} 

它沒有「sock.chat」什麼,我是新來這個很抱歉,如果有一個明顯的錯誤。如果有幫助,我在網站上的Tampermonkey上使用此腳本。

+0

什麼是錯誤,你檢查你的控制檯? –

+0

沒有輸出,如果你把這個URL放到你的瀏覽器中,它會出現文本,但不會輸出到控制檯。它也沒有出現錯誤。 –

回答

1

這裏是一個工作示例:

const url = "https://opentdb.com/api.php?amount=10&token=d6685dc31db69e33eeb1c3828ffa2c587d5ec43dc6dd995ebefe85681796d149"; 
 

 

 
fetch(url) 
 
    .then(res => res.json()) 
 
    .then(json => console.log(json.results)) 
 
    .catch(error => console.error(error))

+0

出於某種原因:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[Object Objec –

1

此代碼工作。

$.get("https://opentdb.com/api.php?amount=10&token=d6685dc31db69e33eeb1c3828ffa2c587d5ec43dc6dd995ebefe85681796d149", function(data, status) { 
 
    console.log(data); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

It仍然沒有任何東西,也許是因爲我使用Tampermonkey? –

0

你可以看到下面的代碼API響應的細節。

$.get("https://opentdb.com/api.php?amount=10&token=d6685dc31db69e33eeb1c3828ffa2c587d5ec43dc6dd995ebefe85681796d149", function(data, status) { 
for(i = 0 ; i <data.results.length; i++){ 
    alert("category: " + data.results[i].category + "\n " + 
      "correct_answer: " + data.results[i].correct_answer + "\n " + 
      "difficulty: "+ data.results[i].difficulty + "\n " + 
      "incorrect_answers: " + data.results[i].incorrect_answers.length + "\n " + 
      "question: " + data.results[i].question + "\n " + 
      "type: " + data.results[i].type + "\n\n\n " + 
      "status: " + status); 
} 

});

您可以使用dom元素而不是「alert」函數來操作響應。

+0

感謝您的回答,但仍然沒有任何東西..除了得到什麼方法嗎? –

+0

您是否在您的HTML頁面中添加了Jquery庫?----------- ----------- you應該「query-1.10.2.js」至於HTML文件的位置。 –

+0

我認爲** sock.chat **不是命令JavaScript。 –