html5的ajax学习(实战篇)
2016-07-26 本文已影响59人
Xcode8
一、百度的智能搜索提醒
2016-07-26_08-05-31.gif二、代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>百度</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js">
</script>
<style>
#sug{
position: relative;
margin-top: 100px;
width: 200px;
height: 400px;
margin-left: 200px;
background-color: aquamarine;
}
#keyWord{
position: absolute;
margin-left: 5px;
margin-top: 10px;
}
#btn{
position: absolute;
margin-left: 138px;
margin-top: 12px;
}
li{
list-style: none;
}
#list{
position: absolute;
margin-top: 35px;
margin-left: 1px;
margin-right: 0;
background-color: lightgray;
}
#list ul li{
margin-left: -35px;
margin-right: 0;
}
</style>
</head>
<body>
<div id="sug">
<div>
<input type="text" id="keyWord" autocomplete=off>
<input type="button" value="百度一下" id="bin">
</div>
<div id="list"></div>
</div>
<script type="text/javascript">
$(function () {
$('#keyWord').keyup(function (e) {
var kd = $('#keyWord').val();
alert(kd);
var url = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+kd;
querySUG(url);
});
});
function querySUG (url) {
document.getElementById('list').innerHTML = '';
$.ajax({
type:"get",
async:true,
url:url,
dataType:"jsonp",
jsonp:"cb",
// jsonCallback:"callback",
success:function (data) {
//解析方法1
// var tag = '<ul>';
// for(var i = 0;i < data.s.length;i++){
// tag += '<li>'+data.s[i]+'</li>';
// }
// tag += '</ul>';
// $('#list').html(tag).show();
// $('#list').find('li').hover(function () {
// $(this).css('background', 'lightGreen');
// },function(){
// $(this).css('background', 'lightGray');
// });
//解析方法2
var ul = $("<ul></ul>");
$.each(data.s,function (i,element) {
var ele = $("<li></li>").append(element);
$(ul).append(ele);
});
$("#list").append(ul);
},
error:function () {
console.log('fail');
}
})
}
</script>
</body>
</html>
三、jquery的遍历方法
1.普通数组
var arr1 = [0, 3, 5];
$.each(arr1,function (i) {
alert(arr1[i]);
});
结果:0,3,5
2.json对象
var jsonData = {"tom": 20, "jerry": 21 };
$.each(jsonData,function (key, value) {
alert(key + "_" + value);
});
结果:tom_20, jerry_21
$.each(jsonData,function (i) {
alert(jsonData[i]);
});
结果:20,21
3.json对象数组($.getJSON里面常用)
var jsonArray = [ { "tom": 20, "jerry": 21 }, { "tom": 22,"jerry": 23} ];
$.each(jsonArray,function (i) {
alert(jsonArray[i].tom);
});
结果:20,22
遍历参考:IT徐胖子的专栏http://blog.csdn.net/woshixuye/article/details/7416949