JSONP处理跨域使用流程:
声明有一个形参的函数,这个形参能拿到我们请求的数据。
在需要下载数据的时候,动态创建script标签,将标签的src属性设置成下载数据的链接。
当script插入到页面上的时候就会调用已经封装好的函数,将我们需要的数据传过来。
实战项目:
最终我们要实现百度下拉框这么一个效果,当我们在输入框输入关键词时,会出现相应的下拉,当我们点击下拉上的选项或者直接点击"百度"按钮时,就会跳转到百度搜索结果页。比如,当我输入"我是"之后,效果如下:
当我点击下拉选项里的"我是余欢水"之后,会跳到新的页面,效果如下:
代码如下:
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>百度下拉框title> <style> #div1 { width: 800px; height: 500px; position: relative; margin: 200px auto; } #div1 #q { height: 40px; width: 680px; position: absolute; top: 0; padding-left: 20px; outline: none; border: 2px solid #f0e3af; left: 0; } #div1 #btn { width: 93px; height: 42px; display: block; position: absolute; top: 0; right: 0; text-align: center; line-height: 42px; cursor: pointer; border: 2px solid #f0e3af; border-left: 1px solid #f0e3af; border-radius: 0 15px 15px 0; } #div1 a { color: rgb(0, 183, 255); } #div1 a:link { text-decoration: none !important; } #div1 #ul1 { list-style: none; width: 700px; position: absolute; top: 30px; left: -40px; } #div1 #ul1 li { width: 684px; padding-left: 20px; border-bottom: 1px solid #f0e3af; background: #ff9800; color: #fff; height: 30px; line-height: 30px; } #div1 #ul1 li a { text-decoration: none; font-size: 16px; color: #fff; }style> <script> function download(data) { // alert("下载的数据是:" + data); // alert(JSON.stringify(data)); var arr = data.s; var oUl = document.getElementById("ul1"); oUl.innerHTML = ""; //每一次创建节点插入数据之前都将上一次数据清空 oUl.style.display = "block"; for (var i = 0; i < arr.length; i++) { var newLi = document.createElement("li"); var oA = document.createElement("a"); oA.innerHTML = arr[i]; oA.href = "http://www.baidu.com/s?wd=" + arr[i]; oA.target = "_blank"; //将a标签插入到li标签上,然后将li标签插入到ul标签上 newLi.appendChild(oA); oUl.appendChild(newLi); } }script> <script> window.onload = function () { var oQ = document.getElementById("q"); var oUl = document.getElementById("ul1"); var oBtn = document.getElementById("btn"); oQ.onkeyup = function () { // alert(this.value) var oValue = this.value; if (!oValue) { oUl.style.display = "none"; } else { //加载数据 var oScript = document.createElement("script"); oScript.src = `http://suggestion.baidu.com/su?wd=${this.value}&cb=download`; document.body.appendChild(oScript); //当用户点击搜索按钮时 oBtn.onclick = function () { oBtn.href = "http://www.baidu.com/s?wd=" + oValue; oBtn.target = "_blank"; }; } }; };script>head> <body> <div id="div1"> <input type="text" id="q" /> <a id="btn">百度a> <ul id="ul1">ul> div> body>html>