客服端
<button class="btn">按钮</button>
<div class="jsonp">
</div>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$('.btn').click(()=>{
$('.jsonp').append('<script src="http://127.0.0.1:3000?callback=show&username=tom"></script>')
})
function show(hao){
console.log(hao);
$('.jsonp>script').eq(0).remove();
}
</script>
服务端(node服务器)
const koa = require('koa');
const app = new koa();
const router = require('koa-router')();
router.get('/',async (ctx,next)=>{
const mysql = {
username : 'tom',
code: 100
};
let code = '';
if(ctx.request.query.username == mysql.username){
code = mysql.code;
}
ctx.body = `${ctx.request.query.callback}(${code})`;
})
app.use(router.routes(),router.allowedMethods());
app.listen(3001,(err)=>{
console.log('连接服务器成功!');
})