前端
同源策略并不会拦截静态资源请求,那么就将接口伪装成资源,然后后端配合返回一个前端预定义的方法调用,将返回值放入调用该函数的形参即可
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title> ???<script> ???????//前端预定义 ???????function getName(rep){ ???????????document.write(rep.name) ???????????console.log(rep) ???????} ???</script></head><body> ???<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> ???<script src="http://localhost:8082?callback=getName"></script></body></html>
后端
后端以node为例,其他语言大同小异
var http = require("http");const url = require("url");http.createServer(function (request, response) { ???let params = url.parse(request.url,true); ???response.end(params.query.callback + `(${JSON.stringify({name:"abc"})})`);}).listen(8082);
效果
补充
当然了,如果你觉得麻烦,你可以用jq的jsonp或者其他封装ajax支持jsonp的插件,效果一样
<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>Title</title> ???<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> ???<script> ???????let url=‘http://localhost:8082?callback=getName‘; ???????$.ajax({ ???????????url: url, ???????????type: "get", ???????????dataType: "jsonp", ???????????jsonpCallback: "getName", ???????????success: function (rep) { ???????????????document.write(rep.name) ???????????????console.log(rep) ???????????} ???????}) ???</script></head><body></body></html>
跨域问题-jsonp
原文地址:https://www.cnblogs.com/dshvv/p/9580036.html