我得到了這個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