源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JSONP跨域请求

  • 时间:2020-02-05 13:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JSONP跨域请求
[b]什么是跨域:[/b] 1、域名不同 2、域名相同端口不同 js出于对安全考虑不支持跨域请求。我们可以使用JSONP解决跨域问题。 [b]一、JSONP是什么[/b] JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。由于同源策略,一般来说位于 server1.example.com 的网页js是无法与不是 server1.example.com的服务器沟通,而 HTML 的<script> 元素是一个例外。利用 <script> 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。 [b]原理:[/b]浏览器在js请求中,是允许通过script标签的src跨域请求,可以在请求的结果中添加回调方法名,在请求页面中定义方法,既可获取到跨域请求的数据。(js请求的不是一个单纯的json数据而是一段包含json数据的js脚本) [img]http://files.jb51.net/file_images/article/201703/201703021413384.png[/img] [b]二、模拟JSONP[/b] 服务器域名:[url=http://localhost:8081/rest/itemcat/list]http://localhost:8081/rest/itemcat/list[/url] 客户端服务器:[url=http://localhost:8082/test.html]http://localhost:8082/test.html[/url] [b]1、普通的JS跨域请求[/b] 服务器数据: [img]http://files.jb51.net/file_images/article/201703/201703021413385.png[/img] 客户端请求代码:
$(function(){
  $.ajax(    {url: "http://localhost:8081/rest/itemcat/list?callback=myFunction", 
     success: function(data){
      console.info(data)
   }}); 
 });
结果
XMLHttpRequest cannot load http://localhost:8081/rest/itemcat/list?callback=myFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.
[b]2、模拟JSONP请求[/b] 客户端请求代码:
$(function(){
  greateScript("http://localhost:8081/rest/itemcat/list");
  function greateScript(src) {
   $("<script><//script>").attr("src", src).appendTo("body")
  } 
 });
结果: [code]list?_=1488425374097:1 Uncaught SyntaxError: Unexpected token :[/code] [b]三、使用JSONP[/b] 环境: 服务器域名:[url=http://localhost:8081/rest/itemcat/list]http://localhost:8081/rest/itemcat/list[/url] 客户端服务器:[url=http://localhost:8082/test.html]http://localhost:8082/test.html[/url] 服务端代码(本人使用springmvc4):
@RequestMapping("/itemcat/list")
 @ResponseBody
 public Object getItemCatList(String callback) {
  CatResult catResult = itemCatService.getItemCatList();
  MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(catResult);
  //设置JSONP回调函数
  mappingJacksonValue.setJsonpFunction(callback);
  return mappingJacksonValue;
 }
客户端调用代码:
$(function(){
  $.ajax(
   { url: "http://localhost:8081/rest/itemcat/list", 
    dataType: "jsonp",
    jsonp: "callback",
    success: function(data){
    console.info(data)
   }}); 
 });
结果: [img]http://files.jb51.net/file_images/article/201703/201703021413396.png[/img] 看返回结果可以发现返回的数据不是一段单纯的json数据,而是一段js函数。 以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程素材网!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部