跨域请求json数据

第一次代码中用json请求数据

<html>
<meta charset="utf8">
<head>
</head>

<body>
<input type="button" value="获取JSON数据" onclick="getInfo()" />
</body>
<script src="jquery-3.0.0.js"></script>
<script>
function getInfo(){
  $.ajax({
    type:"post",
    url:"https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC",
    async:true,
    dataType:"json",
    success: function(data){
      data = JSON.parse(data);
      console.log(data);
    }
  })
}
</script>
</html>

报的错误是

XMLHttpRequest cannot load https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

第二次代码中用jsonp请求数据

<html>
<meta charset="utf8">
<head>
</head>

<body>
<input type="button" value="获取JSON数据" onclick="getInfo()" />
</body>
<script src="jquery-3.0.0.js"></script>
<script>
function getInfo(){
  $.ajax({
    type:"post",
    url:"https://kycp5.com/lotteryV2/lotV2Op.do?lotCode=CQSSC",
    async:true,
    dataType:"jsonp",
    success: function(data){
      data = JSON.parse(data);
      console.log(data);
    }
  })
}
</script>
</html>

报的错误是

 Uncaught SyntaxError: Unexpected token :
lotV2Op.do?lotCode=CQSSC&callback=jQuery3000780…_1498482112702&_=1498482112703
 
 从网上搜到的解释
请求到数据是一个纯Json格式的话,是不能用Jsonp方式调用的,
支持Jsonp方式的url返回的一定是js脚本,一般是一句函数调用,
请注意第二种方法中报的错是callback=,=号后面的就是你得到的,
 
callback是客户端页面定义的函数名,JSONP方式会在返回的
Javascript代码里面调用这个函数,JSON数据是当做参数传入方法的
而不是直接返回一个json。
这个地址不支持jsonp,请求来的数据是json,浏览器要把当做Javascript
来解析,遇到 ":" 就报错了。
如果这个地址支持JSONP,应该返回Javascript代码,在代码里面调用
callback函数才对。
 
API出现增强富web应用开发的体验,曾经想通过跨域请求api非常困难
可以使用json-p这样的技术(有安全限制)或者自己搭建服务器。
 
跨域资源共享CORS是一种W3C的规范,允许浏览器进行跨域通信,
通过设置XMLHttpRequest对象,CORS允许开发者像发起同域请求
那样发起跨域请求。
 
A网站想要访问B网站上的一些数据,这种请求是被同源策略所禁止的,
然而,使用CORS,B网站增加些特殊响应头可以允许来自A网站的请求。
 
因此,使用CORS需要服务器和客户端之间相互了解,幸运的是,
如果你是一位客户端开发者,你可以忽略里面的很多细节。
 
使用javascript进行跨域请求
1、创建XMLHttpRequest对象
chorme浏览器,火狐,Opera和Safari都使用XMLHttpRequest对象。
Internet Explorer使用XDomainRequest对象,有和XMLHttpRequest对象
差不多的功能,但是增加了额外的安全防范措施。
有个辅助方法来兼容不同浏览器
 1 function createCORSRequest(method, url) {
 2   var xhr = new XMLHttpRequest();
 3   if ("withCredentials" in xhr) {
 4 
 5     // Check if the XMLHttpRequest object has a "withCredentials" property.
 6     // "withCredentials" only exists on XMLHTTPRequest2 objects.
 7    // "withCredentials"只存在XMLHTTPRequest2对象中
 8     xhr.open(method, url, true);
 9 
10   } else if (typeof XDomainRequest != "undefined") {
11 
12     // Otherwise, check if XDomainRequest.
13     // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
14     xhr = new XDomainRequest();
15     xhr.open(method, url);
16 
17   } else {
18 
19     // Otherwise, CORS is not supported by the browser.
20     xhr = null;
21 
22   }
23   return xhr;
24 }
25 
26 var xhr = createCORSRequest('GET', url);
27 if (!xhr) {
28   throw new Error('CORS not supported');
29 }
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/guoyinglichong/p/7082427.html