微信扫一扫打赏支持

Ajax跨域:Jsonp实例--百度搜索框下拉提示

Ajax跨域:Jsonp实例--百度搜索框下拉提示

一、总结

一句话总结:a、找好接口;b、用script标签的src引入文件(json数据);c、定义及实现上一步引入文件中的函数

 

1、如何找到一个网站的请求的接口?

google浏览器->F12->Network

 

2、Jsonp是什么?

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

 

3、Jsonp和普通json返回的数据的区别是什么?

jsonp返回的数据是带函数的

 

4、为什么我们从不同的域(网站)访问数据需要一个特殊的技术(JSONP )呢?

这是因为同源策略。同源策略,它是由Netscape提出的一个著名的安全策略,现在所有支持JavaScript 的浏览器都会使用这个策略。

 

 

二、Ajax跨域:Jsonp实例--百度搜索框下拉提示

1、相关知识

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

服务端JSONP格式数据

如客户想访问 : http://www.runoob.com/try/ajax/jsonp.php?jsonp=callbackFunction。

假设客户期望返回JSON数据:["customername1","customername2"]。

真正返回到客户端的数据显示为: callbackFunction(["customername1","customername2"])。

 

 

 

 使用可以参考:

JSONP 教程 | 菜鸟教程
http://www.runoob.com/json/json-jsonp.html

 

 

 

2、截图及代码

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <style>
 7 #q {width: 300px; height: 30px; padding: 5px; border:1px solid #f90; font-size: 16px;}
 8 #ul1 {border:1px solid #f90; width: 310px; margin: 0;padding: 0; display: none;}
 9 li a { line-height: 30px; padding: 5px; text-decoration: none; color: black; display: block;}
10 li a:hover{ background: #f90; color: white; }
11 </style>
12 <script>
13 function maiov(data) {
14     
15     var oUl = document.getElementById('ul1');
16     var html = '';
17     if (data.s.length) {
18         oUl.style.display = 'block';
19         for (var i=0; i<data.s.length; i++) {
20             html += '<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+ data.s[i] +'</a></li>';
21         }
22         oUl.innerHTML = html;
23     } else {
24         oUl.style.display = 'none';
25     }
26     
27 }
28 window.onload = function() {
29     
30     var oQ = document.getElementById('q');
31     var oUl = document.getElementById('ul1');
32     
33     oQ.onkeyup = function() {
34         
35         if ( this.value != '' ) {
36             var oScript = document.createElement('script');
37             oScript.src = 'http://suggestion.baidu.com/su?wd='+this.value+'&cb=maiov';
38             document.body.appendChild(oScript);
39         } else {
40             oUl.style.display = 'none';
41         }
42         
43     }
44     
45 }
46 </script>
47 </head>
48 
49 <body>
50     <input type="text" id="q" />
51     <ul id="ul1"></ul>
52 </body>
53 </html>

 

 

 

 
posted @ 2018-08-16 02:15  范仁义  阅读(724)  评论(0编辑  收藏  举报