jsonp 的例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>jsonp 跨域</title> </head> <body> <script> function succ(data) { console.log(data) //Object // p: false // q: "s" // s: Array(10) // 0: "双色球开奖结果" // 1: "sk-ll" // 2: "双色球" // 3: "圣墟" // 4: "switch" // 5: "顺丰快递单号查询" // 6: "神级龙卫" // 7: "沈浪与苏若雪最新章节更新" // 8: "申通快递单号查询" // 9: "soul" // length: 10 // __proto__: Array(0) // __proto__: Object } </script> <script src="http://suggestion.baidu.com/su?wd=S&p=3&cb=succ&from=superpage"> </script> </body> </html>
jsonp 的原理:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> function jsonp({url,params,cb}) { //返回一个promise 的目的是 为了 下面的 then 函数返回数据 return new Promise((resolve,reject)=>{ //创建script let script = document.createElement('script'); // 声明方法 window[cb]= function (data) { resolve(data); //得到数据移除script 标签 document.body.remove(script) } //合并参数 params = {...params,cb}; let arrs = []; //遍历数组 将 wd=S ,cb=succ 以这种形式添加到数组中 for(let key in params ) { arrs.push(`${key}=${params[key]}`) } //链接script script.src = `${url}?${arrs.join('&')}`; //添加到body 中 document.body.appendChild(script) }) } jsonp({ url:'http://suggestion.baidu.com/su?wd=S&cb=succ', params:{ wd:'b' }, cb:'succ' }).then(data=>{ console.log(data); // {q: "s", p: false, s: Array(10)} // p: false // q: "s" // s: (10) ["双色球开奖结果", "sk-ll", "双色球", "圣墟", "switch", "顺丰快递单号查询", "神级龙卫", "沈浪与苏若雪最新章节更新", "申通快递单号查询", "soul"] // __proto__: Object }) </script> </body> </html>
输出: