我得到了这个HTML文件来触发对随机字API(wordnik)服务器的GET请求。它返回的东西是这样的:如何阅读jsonp类型的对象
[{"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>
数据是一个数组,而不是一个简单的对象 –
你可能想'数据[0] .word' – msrd0