Ajax使用jsonp解决跨域实例

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8     <style>
 9         li:hover{
10             background: skyblue;
11         }
12         a{
13             text-decoration: none;
14             color:black;
15         }
16     </style>
17 </head>
18 <body>
19     <input type="text" id="searchInput" placeholder="百度一下,你就知道"/>
20     <ul>
21         <!-- <li><a href="#">111</a></li>
22         <li><a href="#">222</a></li>
23         <li><a href="#">333</a></li>
24         <li><a href="#">44</a></li>
25         <li><a href="#">555</a></li> -->
26     </ul>
27 
28     <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
29     <script>
30         var timeout = null;
31         // 文本框绑定输入事件
32         $("#searchInput").on("input",function(){
33             window.clearTimeout( timeout );
34             timeout = setTimeout(function(){
35                 // 获取文本框输入的值
36                 var searchVal = $(this).val();
37                 if( searchVal == "" ){
38                     $("ul").empty();
39                     return;
40                 }
41                 // 百度搜索建议词条接口: http://suggestion.baidu.com/su?wd=关键字
42                 // 注意: 需要使用jsonp请求方式,并且需要修改callback参数名称为cb
43                 $.ajax({
44                     url: "http://suggestion.baidu.com/su",
45                     dataType: "jsonp",
46                     // 修改callback参数名称
47                     jsonp: "cb",
48                     data: {
49                         wd : searchVal
50                     },
51                     success: function( res ){
52                         var htmlStr = ``;
53                         res.s.forEach( function( item ){
54                             htmlStr += `<li><a href="https://www.baidu.com/s?wd=${item}" target="_blank">${item}</a></li>`;
55                         });
56                         $("ul").html( htmlStr );
57                     }
58                 });
59                 // 百度搜索结果:        http://www.baidu.com/s?wd=关键字
60             }.bind( this ), 200 );
61         });
62     </script>
63 </body>
64 </html>

运行起来后即可模拟百度输入框-->随便点击一个即可跳转

 

转自:https://blog.csdn.net/guoxuying/article/details/122613989

posted @ 2022-07-09 11:09  strongerPian  阅读(232)  评论(0编辑  收藏  举报
返回顶端