使用jsonP实现豆瓣图书的搜索

本次用到的jsonP接口:

  1. 请求回调与与关键词匹配的内容
    http://api.douban.com/book/subjects?q=关键词&alt=xd&callback=回调函数(fn1)

2.设置每页显示条数(max-result)、起始索引(start-index)
http://api.douban.com/book/subjects?q='+oWd.value+'&alt=xd&callback=fn1&start-index=返回的起始(默认为1)&max-results=每页显示的条数(默认为10)

html代码:

1
2
3
4
5
6
7
8
9
10
11
<input type="text" id="wd" autofocus>
<input type="button" value="搜索豆瓣" id="btn">
<p id="msg"></p>
<hr>
<div id="list"></div>
<ul id="page"></ul>

CSS代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<style>
#list {
display: none;
}
#list dl{
border-bottom: 1px dotted darkgoldenrod;
}
#list dl:last-child{
border-bottom: none;
}
#page{
display: none;
padding-bottom: 70px;
}
#page li{
float: left;
list-style: none;
margin-bottom: 5px;
}
#page li a{
padding: 5px 10px;
border: 1px solid #bf6900;
margin-right: 5px;
text-decoration: none;
line-height:2em;
}
#page li a:hover,#page li .active{
background-color: #bf6900;
color: white;
}
#page li a:active{
background-color: #bf6900;
}
</style>

js代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<script>
//回调函数,用于对数据的处理,必须全局
function fn1(data) {
var oMsg = document.getElementById('msg');
var oList = document.getElementById('list');
//搜索结果-标题
oMsg.innerHTML = data.title.$t + ':'+ data['opensearch:totalResults'].$t;
//搜索结果-内容
var aEntry = data.entry;
var html = '';
for(var i=0;i<aEntry.length;i++){
html += '<dl><dt>'+aEntry[i].title.$t+'</dt><dd><img src=" '+aEntry[i].link[2]['@href']+' "/></dd></dl>';
}
oList.innerHTML = html;
oList.style.display = 'block';
//页码生成
var oLis='';
var oPages = data['opensearch:totalResults'].$t/10;
var oWd = document.getElementById('wd');
var oPage = document.getElementById('page');
for(var j =0 ;j<oPages ;j++){
oLis += '<li><a id="'+j+'" onclick="fn2(this.id)">'+(j+1)+'</a></li>';
// var oLi = document.createElement('li');
// var oA =document.createElement('a');
// oA.innerHTML = j+1;
// oA[j].onclick = fn2(this.id);
// oLi.appendChild(oA);
// oPage.appendChild(oLi);
}
oPage.innerHTML = oLis;
oPage.style.display = 'block';
}
//点击页码,展示对应内容
function fn2(obj){
var oWd = document.getElementById('wd');
if (oWd.value!=''){
var oScript = document.createElement('script');
oScript.src = 'http://api.douban.com/book/subjects?q='+oWd.value+'&alt=xd&callback=fn1&start-index='+(obj+1)+'&max-results=10';
document.body.appendChild(oScript);
}
}
//等待DOM完全加载完毕
window.onload = function () {
var oWd = document.getElementById('wd');
var oBtn = document.getElementById('btn');
//点击搜索按钮,触发jsonP跨域请求
oBtn.onclick = function () {
if (oWd.value!=''){
var oScript = document.createElement('script');
oScript.src = 'http://api.douban.com/book/subjects?q='+oWd.value+'&alt=xd&callback=fn1';
document.body.appendChild(oScript);
}
}
}
</script>

效果图:

搜索结果:
搜索结果

翻页:

翻页