其本质是利用了script标签具有可跨域的特性,由服务端返回预先定义好的javascript函数调用,并且将服务端数据以该函数参数的形式传递过来。
为什么要定义callback?首先我们知道,这个get请求发出去后如何接口请求回来的数据,callback=func则可以帮我们做这件事。(需要在客户端声明一个与callback=“func”的func同名的函数,通过jsonp方式成功接收到服务器数据的时候就会自动触发这个回调函数)
<button id="btn">点击</button> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script> $(‘#btn‘).click(function(){ var frame = document.createElement(‘script‘); frame.src = ‘http://localhost:3000/article-list?name=leo&age=30&callback=func‘; $(‘body‘).append(frame); }); function func(res){ alert(res.message+res.name+‘你已经‘+res.age+‘岁了‘); } </script>
router.get(‘/article-list‘, (req, res) => { console.log(req.query, ‘123‘); let data = { message: ‘success!‘, name: req.query.name, age: req.query.age } data = JSON.stringify(data) res.end(‘func(‘ + data + ‘)‘); });
1.通过原生js方式使用jsonp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{ margin: 0; padding: 0; list-style: none; } ul{ background-color: #ccc; width: 172px; } </style> </head> <body> <input type="" name="" id=‘inp‘> <ul> </ul> <script type="text/javascript"> //1获取input //2.注册事件,获取value //3动态创建script //4追加到body、 var inp = document.getElementById(‘inp‘) var ul = document.querySelector(‘ul‘) function suggest_so(data){ console.log(data) var {result} = data ul.innerHTML = ‘‘ for(var i =0;i<result.length;i++){ // 创建li var li = document.createElement(‘li‘) li.innerHTML = result[i].word; ul.appendChild(li) } } inp.oninput = function(){ // 判断创建script是否一致 if(document.getElementsByClassName(‘ss‘).length>0){ document.getElementsByClassName(‘ss‘)[0].remove() } var val = inp.value; var jsonp = document.createElement(‘script‘) jsonp.src = ‘https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=‘+val jsonp.className = ‘ss‘ document.body.appendChild(jsonp) } </script> </body> </html>
2.通过jQuery封装的ajax方式使用jsonp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style type="text/css"> * { margin: 0; padding: 0; list-style: none; } ul { background-color: #ccc; width: 172px; } </style> <script type="text/javascript" src="jquery-1.12.1.js"></script> <script type="text/javascript" src="template-web.js"></script> </head> <body> <input type="" name="" id="inp" /> <ul></ul> <script type="text/html" id="tpl"> {{each result value}} <li>{{value.word}}</li> {{/each}} </script> <script type="text/javascript"> $(function(){ $(‘#inp‘).on(‘input‘,function(){ $.ajax({ url:‘https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=‘+$(this).val(), dataType:‘jsonp‘, jsonpCallback:‘suggest_so‘, success:function(data){ var {result} = data; var str = template(‘tpl‘,{result}) $(‘ul‘).html(str) } }) }) }) </script> </body> </html>
原文:https://www.cnblogs.com/belongs-to-qinghua/p/11353154.html