jsonp跨域请求是借助于表单元素的"src"属性的"跨域"实现的,具体实现如下:
1、html页面
<html>
<head>
<title></title>
</head>
<body>
<script>
var url = "http://localhost:7778/api/test?callbackname=callback";
var script = document.createElement('script');
script.setAttribute('src', url); //load javascript
document.getElementsByTagName('head')[0].appendChild(script);
//回调函数
function callback(data){
alert(data.name);
//var html=JSON.stringify(data.name);
}
</script>
</body>
</html>
2、服务端代码
@RestController
@RequestMapping(value = "/api")
public class JsonpController {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Object view() {
System.out.println("callback({\"id\":1,\"name\":\"test\"})");
return "callback({\"id\":1,\"name\":\"test\"})";
}
}
jsonp和ajax并无关系,只是借助了src属性的"跨域"特性来实现的(json)数据的传输, 当服务器返回的数据是以:foo(data)格式返回时,而此时客户端刚好有一个名为foo的函数,则浏览器便会去调用foo函数,而服务端的数据data以参数的形式完成了向客户端的传递,浏览器以此种方式实现了远程跨域调用