对crossIn api端点发出跨域ajax请求

时间:2016-07-18 05:08:40

标签: jquery ajax cors

我试图通过向linkedIn api端点发出GET请求来获取网站上的分享数量:

https://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json

这是我的代码:

$.ajax({
    url: 'http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json',
    type: 'GET',
    processData: false,
    crossDomain: true,
    contentType: "application/json",
    jsonp: false,
    success: function(data) { alert('succeeded'); },
    error: function() { alert('Failed!'); },
});

当我运行它时,我得到:

XMLHttpRequest cannot load http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://aranca.craft.dev' is therefore not allowed access.`

我做错了什么?如何访问sharedcount数据?

1 个答案:

答案 0 :(得分:3)

您可以使用dataType: 'jsonp'解决此CORS问题,例如:



$.ajax({
  url: 'https://www.linkedin.com/countserv/count/share?url=http://stylehatch.co',
  type: 'GET',
  contentType: "application/json",
  dataType: 'jsonp',
  success: function(data) {
    console.log('Count: ' + data.count);
  },
  error: function() {
    console.log('Failed!');
  },
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
&#13;
&#13;
&#13;