最近学到Ajax,觉得自己对与前后端的数据交互有了一个基本的了解。下面是Ajax应用到淘宝/百度的搜索功能的一个简单的小实例,就是输入一个词,下拉框中自动显示匹配的内容:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXsAAAHrCAIAAAChOqofAAAT1UlEQVR4nO3dL5PdVp7HYb2LhoGBgWYTGBgYGGgY6AoKNHRVNjupRSGTCTQMSplNLzMwMDQIMDQ0WmuBE/u2/hydo3uv3F/peaprqlute6Seqt8n0u1O1PUAW+k+9QkAB6I4wHYUB9iO4gDbURxgO4oDbGe2OC/+fPfv/+19+PBxbz9e/Pluy1hcxHRxXvz57vsf//j1px98+PBxbz++//GPuOhMF+fX23f/+q8ftj0ToM2vP/3wr//836c+izaKA6kUB9iO4gDbURxgO4oDbEdxgO0oDrAdxQG2ozjAdhQH2I7ijFbv/LvpcC2KM1pdceBqFGe0uuLA1SjOaHXFgatRnNHqigNXs//ivH3523dffX7Tdd3N5189/Pn2zYfvvLn9+eH773Q3n3/z+OnLt32vOHBNey/Om98f3tw8fPq67/u+f/304U337dM3fd/3b58/ftB9/fPL91+8/v27L7ovnjzvFQeuae/FuX3cdV//9mq099tn33Xdd8/eDnZ8rThwTXsvztvnjx90N19+++S321dvR6958/L22dNfnjx6+PWDzzrFgavbe3H6vn/z8umTh1991nVd99nHN3Le3j7+8qb77MHXDx/9/Nuzl2+ePVIcuLoDFOdvb1/f/vLdlzfdV7+86vtXv3zVffHo9uSuSnHg+g5UnL7v+/7Zo657fPv+bZuHv38MzvMnXygOXN3ei/P8yRfd1z8//+tO6tVv39zcPHr2tu/fPP22u/nm/VvKb1///uhB13Xvf1mlOHA9ey9O379+9uTbL9//1c1nD759/Purv7a/uX3yzcc/03n28u/fnCsOXM/+i9O8uuLA1SjOaHXFgatRnNHqigNXozjAdhQH2I7iANtRHGA7igNsR3GA7SgOsB3FAbajOMB2FAfYjuIA21EcYDv7Kc6LP999/+Mf//7vH3z48HFvP77/8Y8Xf77bOBlnmv13u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m8An35STpKrG5imOKUj3X1LuLxb+XOg7xVn7hgVlzanOy9+DvT93ouz+Fuq8R3QOCv1X859S3rgL/suzrlH+vuuanGfyd0UB4YUZ+Fga3PzYbu3kOEjxQG2EzikigOxAodUcSBW4JAqDsQKHFLFgViBQ6o4ECtwSBUHYgUOqeJArMAhVRyIFTikigOxAodUcSBW4JAqDsQKHNJicXz48HHPP9LknTGQS3GA7SgOsB3FAbajOMB2FAfYjuIA21EcYDuKA2xHcYDtKA6wHcUBtqM4wHYUB9iO4gDbURxgO4oDbEdxgO0oDrAdxQG2ozjAdhQH2I7iANtRHGA7igNsR3GA7SgOsB3FAbajOMB2FAfYjuIA21EcYDuKA2xHcYDtKA6wHcUBtqM4wHYUB9iO4gDb+X8gnAjHhTN61AAAAABJRU5ErkJggg==" alt="" />
页面的布局比较简单,就是一个input输入框和一个下拉的ul列表:
<body>
<input type="text" id="q" />
<ul id="ul1"></ul>
</body>
给两个框加上简单的样式,ul的display:none;后续在js里面创建元素:
<style>
#q {width: 300px; height: 30px; padding: 5px; border:1px solid #f90; font-size: 16px;}
#ul1 {border:1px solid #f90; width: 310px; margin: 0;padding: 0; display: none;}
li a { line-height: 30px; padding: 5px; text-decoration: none; color: black; display: block;}
li a:hover{ background: #f90; color: white; }
</style>
js中用到Ajax跨域解决方案JSONP:在页面创建一个script标签,设置src属性,加入参数,用函数angel(data)处理获取过来的数据,将数据加入到ul列表中,点击下拉列表中的数据跳转到百度搜索页面:
<script>
function angel(data) { var oUl = document.getElementById('ul1');
var html = '';
if (data.s.length) {
oUl.style.display = 'block';
for (var i=0; i<data.s.length; i++) {
html += '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>';
}
oUl.innerHTML = html;
} else {
oUl.style.display = 'none';
} }
window.onload = function() { var oQ = document.getElementById('q');
var oUl = document.getElementById('ul1'); oQ.onkeyup = function() { if ( this.value != '' ) {
var oScript = document.createElement('script');
oScript.src = 'http://suggestion.baidu.com/su?wd='+this.value+'&cb=angel';
document.body.appendChild(oScript);
} else {
oUl.style.display = 'none';
}
}
}
</script>