Node和Jquery实现Jsonp
Node代码:
var http = require("http"); var url = require('url'); //定时休眠函数 function sleepFun(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds); } //访问地址:http://127.0.0.1:4000/?callback=ccc&name=allen&age=18&_=1491380773607 http.createServer(function(req, res) { //sleepFun(3000); //var arg = url.parse(req.url).query; //callback=ccc&name=allen&age=18&_=1491380773607 var arg = url.parse(req.url,true).query; //{callback:'ccc',name:'allen',age:'18',_'1491380773607'} var callbackName = arg.callback; var responseData = {'code':'A00000','data':'akalaka'}; var responseString = JSON.stringify(responseData); if (callbackName) { var jsonpResponse = callbackName+'('+responseString+')'; res.end(jsonpResponse); } else { res.end(responseString); } // var resHTML = 'try{window.ccc({"code":"A00000","data":{"data":{},"code":"Q00301"}});}catch(e){}'; console.log(req.url); }).listen(4000); console.log("HTTP server is listening at port 4000.");
JS代码:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> <script type="text/javascript"> $(function(){ $("#testAjax").click(function(){ $.ajax({ data: "name=garfield&age=18", url: 'http://i.vip.iqiyi.com/pay/pc/checkSuitInfo.action', //url: 'http://127.0.0.1:4000/', type: "GET", timeout:"15000", dataType: 'jsonp', success: function(data){ console.log('succeed'); }, error: function(e) { console.log(e); }, complete:function(){ console.log(66666); } }); }); $("#testAjaxNode").click(function(){ $.ajax({ data: "name=allen&age=18", //url: 'http://i.vip.iqiyi.com/pay/pc/checkSuitInfo.action', url: 'http://127.0.0.1:4000/', type: "GET", timeout:"1000", dataType: 'jsonp', jsonpCallback:'name123', success: function(data){ console.log('succeed'); }, error: function(e) { console.log(e); }, complete:function(){ console.log(66666); } }); }); }); </script> </head> <body> <button id="testAjax" type="button">线上接口</button> <button id="testAjaxNode" type="button">node测试接口</button> </body> </html>
总结,一开始写死了callback名字,js参数的jsonpCallback和node返回的callback名字不一样,导致客户端js回调为error,success的回调无法执行。