当然后端输出普通的json字符串是不行的,后台应当输出fn(json)样式的字符串,fn代表要调用的js方法;json代表要处理的数据.这也是jsonp得名的原因.后台不会知道要调佣哪个js,所以需要前台把要调用的函数的名字发给后台.
一个简单的jsonp例子
后台 node版本
var http = require('http'); var server = new http.Server(); server.listen(8000); server.on('request',function(request,response){ var url = require('url'); var params = url.parse(request.url,true).query; var fn = params.fn; response.writeHead(200,{'Content-type':'text/plain'}); response.write(fn+'(22)'); response.end(); });
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title></title> <script> var log = function(msg) { alert(msg); } </script> </head> <body> <script type="text/javascript"> function getJsonp(url,fn) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.onload = function() { head.removeChild(script); if (fn) { fn(); } } script.src = url; head.appendChild(script); } getJsonp("http://192.168.1.103:8000/?fn=log"); </script> </body> </html>原文链接:https://www.f2er.com/json/290052.html