调用有道词典 源码
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
window.onload = function () {
function searchSingleWord(word) {
return new Promise((resolve, reject) => {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlHttp.responseText, "text/html")
xmlDoc = xmlDoc.querySelector("div[id='phrsListTab']");
// 音标
let pronounce = "";
xmlDoc.querySelectorAll("span[class='pronounce']").forEach(span => {
let childs = span.childNodes;
pronounce += childs[0].textContent.trim() + childs[1].textContent.trim() + "<br/>";
});
// 翻译
let trans = "";
xmlDoc.querySelectorAll("div[class='trans-container'] ul li").forEach(li => { trans += li.textContent + "<br/>" });
resolve({
word: word,
trans: trans,
pronounce: pronounce
})
} else {
console.error(xmlHttp.responseText);
reject(xmlHttp.responseText);
}
}
};
xmlHttp.open('GET', "/api/yd/" + word, true);
xmlHttp.send();
});
}
function search(word) {
if (word.indexOf(";") > -1) {
word.split(";").forEach(word => {
if (word.trim() == "") {
return;
}
searchSingleWord(word).then((data) => {
let wordLine = document.createElement("div");
wordLine.textContent = "|" + data.word + "|" + data.trans + "|" + data.pronounce + "|";
document.getElementById("markdown").appendChild(wordLine);
});
});
} else {
searchSingleWord(word).then((data) => {
document.getElementById("divResult").innerHTML = '<a href="http://www.youdao.com/w/eng/' + data.word + '">有道链接</a><br/><h4>' + data.word + '</h4>音标:<br/>' + data.pronounce + '<br/>翻译:<br/>' + data.trans + '<hr />';
let wordLine = document.createElement("div");
wordLine.textContent = "|" + data.word + "|" + data.trans + "|" + data.pronounce + "|";
document.getElementById("markdown").appendChild(wordLine);
})
}
}
document.getElementById("btnSearch").onclick = function () {
var word = document.getElementById("txtWord").value;
search(word);
}
document.getElementById("btnReset").onclick = function () {
document.getElementById("txtWord").value = "";
document.getElementById("divResult").innerHTML = "";
document.getElementById("markdown").innerHTML = "|英文|中文|音标|<br/>|---|---|---|<br/>";
}
}
</script>
</head>
<body>
<input id="txtWord" type="text" /><button id="btnSearch">查询</button><button id="btnReset">清空</button><br />
<div id="divResult"></div>
<div id="markdown">|英文|中文|音标|<br />|---|---|---|<br /></div>
</body>
</html>