【发布时间】:2017-10-22 07:28:05
【问题描述】:
我得到这个 HTML 文件来向随机词 API (wordnik) 服务器发出 GET 请求。它返回如下内容:
[{"id":2998982,"word":"failproof"}]
我只想要"word" 部分,但不知道如何访问它。我以为是data.word,但它只是打印了undefined。
<!DOCTYPE html>
<html>
<head>
<title>Random Word Generator</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function generateRandomWord() {
var randomWordURL = "http://api.wordnik.com:80/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=APIkey";
$.ajax({
type: "GET",
url: randomWordURL,
dataType: "jsonp",
jsonpCallback: 'displayRandomWord'
});
}
function displayRandomWord(data) {
document.getElementById("randomword").innerHTML=data.word;
}
</script>
<body onload="generateRandomWord()">
<div id="randomword"></div>
</body>
</html>
【问题讨论】:
-
数据是一个数组,而不是一个普通的对象
-
你可能想要
data[0].word
标签: javascript html json ajax wordnik