【基础概念】基础概念:使用Jsonp 实现跨域的+【[项目深入】调用百度的jsonp完成搜索功能

本文介绍了Jsonp的基本概念,包括什么是Jsonp、为什么要使用Jsonp,以及如何实现Jsonp。并通过一个实际项目,详细讲解如何调用百度搜索API,实现搜索功能,包括页面布局、样式处理和JavaScript操作。最后提供了源码,并提醒读者不要滥用技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一基础概念:

1.Jsonp |是什么?

  1. Jsonp(JSON with Padding) 是 json的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
  2. 用通俗的话来说就是:通过把连接放到< script >标签的src中 src=”连接” 这个连接可以不受同源策略的限制 进而获得数据 一般来说jsonp 请求过来的数据
  3. 是一个执行的函数 请求的后台 返回一个add(number) add 是后台定义的函数名字 number是后台查询数据库的结果把结果打包成函数 返回过来 前端在页面直接定义同名的函数add(arg) 参数就是返回的数据进行处理即可
  4. 当script 的src 获得返回的函数add(number) 页面的add函数就会执行 此时前端已做好add函数的功能

2.Jsonp |为什么?

**为什么我们需要jsonp呢?**
  1. 因为浏览器的同源策略 因为这种安全策略 不能跨域 需要协议 ip 端口 相同才能请求
    http://localhost:4000 请求 https://localhost:4000 http|https协议不同
    http://localhost:4000 请求 http://localhost1:4000 localhost|localhost1 ip不同
    http://localhost:4000 请求 http://localhost:4001 4000|4001端口不同
当前地址请求地址差异结果
https://localhost:4000http://localhost:4000ttp https协议不同
http://localhost:4000http://localhost1:4000localhost localhost1ip不同
http://localhost:4000http://localhost:40014000 4001端口不同
  1. 技术需求 jsonp使用之前呢 像是ajax axios等异步请求的功能库 还没登上舞台
  2. 也就是说当时是不能通过ajax 进行跨域处理 或是配置proxy等 所以最直接的就是使用jsonp 但是现在ajax axios逐渐优化 顺应需求
  3. jsopn的使用也就少了 但是jsonp的技术依然存在 也有很多使用的地方

3.Jsonp |怎么做?

找一个jsonp的项目练练手 了解jsonp的使用场景和使用方法

4.Jsonp |会怎样?

你猜会怎样?装逼啊! 别人都是懂,你是做过案例项目的人

二项目深入:

1.项目介绍

	这个小demo 或是小项目 就是实现百度搜索框的功能
	百度能搜索什么  我们也是可以的
	到时候买个服务器,部属个网站,提供百度搜索的功能 多NB

在这里插入图片描述

这个页面看起来很俗 但是他的数据是来源 百度的哟
一比一的数据绝无参假信息 点击就会跳转

2.获得百度的查询连接 之后赋值给script

在这里插入图片描述

  • 1.打开控制台 F12
  • 2.找到network
  • 3.在输入框中 输入信息
  • 4.监听请求su…
  • 5.获得数据

在这里插入图片描述

3.分析url

在这里插入图片描述
不难看出 你input输入的值 就是在其中与对应的字段 其他的可以不用动
那么我们 只要可以修改这个url 那么是不是就可以拿到很多的数据
有没有兴奋?

4.页面布局

<body>
    <div class="searchBox">
        <input type="text" placeholder="二次元程序员" id="searchInput">
        <button>嗖一下</button>
        <!-- //下拉框 展示搜索的数据 -->
        <ul class="itemBox">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
</body>

5.样式处理

1.清控全局默认样式

 * {
    margin: 0;
    padding: 0;
 }

2.body 铺满全屏

body {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
        background-color: #333;
    }

3.布局输入框和按钮的排列分布样式

变成弹性盒模型
让input 和button 靠边排列

.searchBox {
           position: relative;
           display: flex;
           justify-content: space-between;
           align-items: center;
           width: 500px;
           height: 100px;
           padding: 0 5px;
           /* overflow: hidden; */
           background-color: aliceblue;
       }

4.完善输入框的样式

.searchBox input {
        width: 400px;
        height: 44px;
        outline: 0;
        font-size: 16px;
        text-indent: 20px;
        border-radius: 4px;
        outline: 1px solid #333;
        border: 1px solid #333;
    }

5.完善button的样式

 .searchBox button {
        width: 70px;
        height: 40px;
        border-radius: 4px;
        color: #fff;
        outline: 1px solid #333;
        background-color: skyblue;
        border: 1px solid #333;
    }

6.设置ul 显示查询结果的样式

ul {
    position: absolute;
     top: 74px;
     list-style: none;
     width: 400px;
     overflow: hidden;
     transition: 0.5s linear;
     background-color: aliceblue;
 }

7.设置ul 显示隐藏

当输入值为空 ul js设置 height:0 其他的边框 也要清除
当输入有值 ul height:345+‘px’ 每个li高度li的数量 其他的边框 也要显示
此样式用于 消除|显示 边框
当存在是 添加itemstyle 不存是取消itemstyle

 .itemstyle{
     padding: 14px 0;
      border-radius: 4px;
      border: 2px solid #333;
  }

8.设置li的样式

li{
   line-height: 34px;
    text-indent: 20px;
    white-space: nowrap;
    text-overflow: ellipsis;
}

9.设置li 鼠标放上去的 样式

li:hover{
  	cursor: pointer;
    background-color: antiquewhite;
 }

6.js操作

1. 获取操作元素

//获得 input
    var searchInput = document.querySelector("#searchInput")
//获得 ul        
	Var itemBox=document.querySelectorAll('.itemBox')
//获得 li
    var itemBoxLi=document.querySelectorAll('.itemBox li')

2.给input添加输入事件

searchInput.addEventListener('input', search)

3.完善input的输入事件处理

处理的逻辑

  • 1.获得数据框的值
    进行非空判断
	if (!this.value) {
			//不存在  隐藏ul
         itemBox[0].classList.remove('itemstyle')
         itemBox[0].style.height='0px'
     }else{
		//存在  展示ul
         itemBox[0].classList.add('itemstyle')
         itemBox[0].style.height=34*5+'px'
     }
  • 2.创建script
 var myScript = document.createElement('script')
  • 3.设置script的属性
  myScript.language = 'javascript';
  myScript.type = 'text/javascript';
  • 4.处理script的src 的动态实现
    把script 要请求的url --上面的url分析的url 赋值上去
//把输入的值 转码
var codeValue = encodeURI(this.value)
//创建连接的摸班字符串  

 var srcadds = `
            https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36176,31253,36165,34584,36121,36075,35994,35956,26350,36111,36101,36061&wd=${codeValue}&req=2&pbs=${codeValue}&csor=3&pwd=${codeValue}&cb=jQuery110208583473030013036_1648427901748&_=1648427901752
            `
 myScript.setAttribute('src', srcadds.trim())
  • 5.把script放到页上
 document.body.appendChild(myScript)
  • 6.处理原生的js script动态修改的问题
    在js中 将script第一次插入页面后会根据src 发出请求
    但是之后 通过js修改script的src 是不会再发请求的
    这是原生的行为
    所以要解决方法: 创建一个插入获得数据 后 再删除\
setTimeout(()=>{
  myScript.remove()
 },4000)

input 输入一次函数激活一次 创建script 插入页面 获得数据 删除

7.处理请求获得的数据 生成li的内容

请求的数据在这里插入图片描述
这就是jsonp获得的数据
发现没有他就是个函数*
jQuery110208583473030013036_1648427901748(res)* 并且执行函数的代码
也就是说script 请求后你的js代码对应的函数就会执行

        //获得json的数据 并执行
        var JsonpData = null
        function jQuery110208583473030013036_1648427901748(res) {
            //分析可以 g 就是结果
            //结果为空拦截 
            
            if (!res.g) {
                return 
            }
            //把res 转换为对象
            JsonpData = JSON.parse(JSON.stringify(res))
            ////循环式的给li 添加数据
            itemBoxLi.forEach((ele,index)=>{
                ele.innerHTML=JsonpData.g[index].q
            })
        }

8.给li添加打开网页的能力

 //itemBoxLi 添加点击事件
        itemBoxLi.forEach(ele=>{
        	//获得每个li 添加点击事件
            ele.onclick=function(){
            	//获得每个li的文字
                var codevalue=encodeURI(this.innerHTML)
                window.open(`https://www.baidu.com/s?wd=${codevalue}&rsv_spt=1&rsv_iqid=0xe6857b050026d9f6&issp=1&f=3&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_dl=ih_0&rsv_sug3=1&rsv_sug1=1&rsv_sug7=001&rsv_sug2=1&rsv_btype=i&rsp=0&rsv_sug9=es_2_1&inputT=5177&rsv_sug4=5177&rsv_sug=2`)
            }
        })

open中url的来历
在这里插入图片描述
在这里插入图片描述
稍作分析就知道了
直接把上面的url复制下来 动态的修改 wd的值就可以了

三:懒人福利-源码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #333;
        }

        .searchBox {
            position: relative;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 500px;
            height: 100px;
            padding: 0 5px;
            /* overflow: hidden; */
            background-color: aliceblue;
        }

        .searchBox input {
            width: 400px;
            height: 44px;
            outline: 0;
            font-size: 16px;
            text-indent: 20px;
            border-radius: 4px;
            outline: 1px solid #333;
            border: 1px solid #333;
        }

        .searchBox button {
            width: 70px;
            height: 40px;
            border-radius: 4px;
            color: #fff;
            outline: 1px solid #333;
            background-color: skyblue;
            border: 1px solid #333;
        }

        ul {
            position: absolute;
            top: 74px;
            list-style: none;
            width: 400px;
            overflow: hidden;
            transition: 0.5s linear;
            background-color: aliceblue;
        }
        .itemstyle{
            padding: 14px 0;
            border-radius: 4px;
            border: 2px solid #333;
        }
        li{
            line-height: 34px;
            text-indent: 20px;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
        li:hover{
            cursor: pointer;
            background-color: antiquewhite;
        }
    </style>
</head>

<body>
    <div class="searchBox">
        <input type="text" placeholder="二次元程序员" id="searchInput">
        <button>嗖一下</button>
        <!-- //下拉框 -->
        <ul class="itemBox">
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
    <script>
        //获得 input
        var searchInput = document.querySelector("#searchInput")
        var itemBox=document.querySelectorAll('.itemBox')
        var itemBoxLi=document.querySelectorAll('.itemBox li')
        searchInput.addEventListener('input', search)
        function search() {
            if (!this.value) {
                itemBox[0].classList.remove('itemstyle')
                itemBox[0].style.height='0px'
            }else{
                itemBox[0].classList.add('itemstyle')
                itemBox[0].style.height=34*5+'px'
            }
            //插入
            var myScript = document.createElement('script')
            var codeValue = encodeURI(this.value)
            myScript.language = 'javascript';
            myScript.type = 'text/javascript';
            var srcadds = `
            https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36176,31253,36165,34584,36121,36075,35994,35956,26350,36111,36101,36061&wd=${codeValue}&req=2&pbs=${codeValue}&csor=3&pwd=${codeValue}&cb=jQuery110208583473030013036_1648427901748&_=1648427901752
            `
            myScript.setAttribute('src', srcadds.trim())
            document.body.appendChild(myScript)
            setTimeout(()=>{
                myScript.remove()
            },4000)
        }
        //获得json的数据 并执行
        var JsonpData = null
        function jQuery110208583473030013036_1648427901748(res) {
            if (!res.g) {
                return 
            }
            JsonpData = JSON.parse(JSON.stringify(res))
            itemBoxLi.forEach((ele,index)=>{
                ele.innerHTML=JsonpData.g[index].q
            })
        }
        //itemBoxLi 添加点击事件
        itemBoxLi.forEach(ele=>{
            ele.onclick=function(){
                var codevalue=encodeURI(this.innerHTML)
                window.open(`https://www.baidu.com/s?wd=${codevalue}&rsv_spt=1&rsv_iqid=0xe6857b050026d9f6&issp=1&f=3&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_dl=ih_0&rsv_sug3=1&rsv_sug1=1&rsv_sug7=001&rsv_sug2=1&rsv_btype=i&rsp=0&rsv_sug9=es_2_1&inputT=5177&rsv_sug4=5177&rsv_sug=2`)
            }
        })

    </script>

    <!-- <script src="https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36176,31253,36165,34584,36121,36075,35994,35956,26350,36111,36101,36061&wd=%E7%96%AB%E6%83%851&req=2&pbs=%E7%96%AB%E6%83%85&csor=3&pwd=%E7%96%AB%E6%83%85&cb=jQuery110208583473030013036_1648427901748&_=1648427901752"></script> -->



</body>

</html>

四:个人声明

以上接口是百度的api
浏览器几乎天天调用这些接口
我只是分享了出来
请不要利用技术搞破坏…出现问题概不负责
我只是一个喜欢二次元的程序员 才2年而已

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值