Ajax 解夢&垃圾分類 接口調(diào)用
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<style>
* {
margin: 0;
padding: 0;
}
.top {
width: 80%;
height: 100px;
position: relative;
top: 200px;
left: 100px;
text-align: center;
font: 18px/30px 'courier new';
}
#func{
font: 18px/30px 'courier new';
}
#word {
text-align: center;
font: 18px/30px 'courier new';
border: none;
outline: none;
border-bottom: 1px solid gray;
}
#search {
width: 60px;
height: 40px;
font: 18px/30px 'courier new';
}
#container {
width: 80%;
height: 100%;
position: relative;
top: 250px;
left: 100px;
text-align: center;
font: 18px/30px 'courier new';
}
</style>
</head>
<body>
<div class="top">
<select id="func">
<option value="0" selected>周公解夢</option>
<option value="1">垃圾分類</option>
</select>
<input type="text" id="word">
<button id="search">查詢</button>
</div>
<div id="container"></div>
</body>
<script src="../js/jquery.min.js"></script>
<script>
$(() => {
const container = $('#container')
// const key = 'f82260eff0d31183dd10d8327a148b98'
// const num = 10
const URLs = [
'http://api.tianapi.com/txapi/dream/',
'http://api.tianapi.com/txapi/lajifenlei/'
]
const clsssedList = ['可回收垃圾', '有害垃圾', '濕垃圾', '干垃圾']
const selected = $('#func')
const input = $('#word')
let selectIndex = selected.val()
let selectURL = URLs[selectIndex]
function doAjaxSearch() {
let word = input.val().trim()
if (word.length <= 0) {
input.val('')
return
}
container.empty()
$.ajax({
url: selectURL,
type: 'get',
data: {
key: 'Your Key',
num: 10,
word: input.val()
},
dataType: 'json',
headers: {
},
success: (json) => {
let results = json.newslist
if (selectIndex == 0) {
for (res of results) {
container.append(
$('<div>').html(res.result)
)
}
} else if (selectIndex == 1) {
for (res of results) {
container.append($('<p>').text(`${res.name}: ${clsssedList[res.type]}`))
}
}
},
error: (err) => {}
})
input[0].focus()
}
selected.on('change', (evt) => {
selectIndex = selected.val()
selectURL = URLs[selectIndex]
input.val('')
container.empty()
})
input.on('keyup', (evt) => {
if (evt.keyCode == 13) {
doAjaxSearch()
}
})
$('#search').on('click', doAjaxSearch)
})
</script>
</html>