如何设置此API获取请求?

时间:2017-05-28 09:11:25

标签: javascript

我正在努力让API工作,从这个网站获得琐事问题:https://opentdb.com/api_config.php。这是我的代码:

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上使用这个脚本。

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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>

答案 2 :(得分: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元素而不是&#34; alert&#34;来操纵响应。功能

相关问题