我正在尝试使用HTML和Javascript创建一个“猜词游戏”,想通过使用Wordnik API来获取一个随机单词。但我不知道如何获取单词并返回它。我已经注册了apiKey,但是我不太清楚如何使用API的AJAX和JSON部分,以及如何与Javascript结合使用。
http://api.wordnik.com:80/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5
你需要一个随机单词列表,并且限制只返回一个单词(limit=1
)。
请使用你自己的api_key
而不是文档中提供的演示密钥。
参考资料:
有点晚了,但现在所有人都在使用React来完成各种任务,因此您可以尝试这样做:
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
const wordnik = 'https://api.wordnik.com/v4/words.json/randomWord?&minLength=5&maxLength=-1&api_key=';
const API_KEY = '';
class FetchData extends React.Component {
state = {
word: '',
}
componentDidMount() {
fetch(wordnik + API_KEY)
.then(res => res.json())
// Uncomment here if you have API_KEY
// .then(json => this.setState({ word: json.word }))
// Comment here if you have API_KEY
.then(json => this.setState({ word: json.message }))
.catch(err => console.log(err.message));
}
render() {
return <h1>{this.state.word}</h1>;
}
}
ReactDOM.render(<FetchData />, document.getElementById('root'));
</script>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
const wordnik = 'https://api.wordnik.com/v4/words.json/randomWord?&minLength=5&maxLength=-1&api_key=';
const API_KEY = '';
class FetchData extends React.Component {
state = {
word: '',
}
componentDidMount() {
fetch(wordnik + API_KEY)
.then(res => res.json())
// Uncomment here if you have API_KEY
// .then(json => this.setState({ word: json.word }))
// Comment here if you have API_KEY
.then(json => this.setState({ word: json.message }))
.catch(err => console.log(err.message));
}
render() {
return <h1>{this.state.word}</h1>;
}
}
ReactDOM.render(<FetchData />, document.getElementById('root'));
</script>