那这篇博客就介绍JSONP方式。
JSONP原理
而JSONP就是通过script节点src调用跨域的请求。
举个例子
客户端http://localhost:8080访问服务器http://localhost:11111/user,正常情况下,这是不允许的。因为这两个URL是不同域的。
若我们使用JSONP格式发送请求的话?
http://localhost:11111/user?callback=callbackfunction
则服务器返回的数据如下:
callbackfunction({"id":1,"name":"test"})
注意:其中URL地址中的callback和callbackfunction是随意命名的。
具体的JS实现JSONP代码。
JS中:
@H_403_66@
- <script>
- varurl="http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=callbackfunction";
- varscript=document.createElement('script');
- script.setAttribute('src',url);//loadjavascript
- document.getElementsByTagName('head')[0].appendChild(script);
- //回调函数
- functioncallbackfunction(data){
- varhtml=JSON.stringify(data.RESULTSET);
- alert(html);
- }