Ajax Jquery CORS无法正常工作 [英] Ajax Jquery CORS not working

查看:397
本文介绍了Ajax Jquery CORS无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我正在努力并从3天开始寻找有关此问题的解决方案.我从sharethis.com RESTapi获取数据时遇到问题.我正在使用jQuery和Laravel 5.2.我想从此json获取值: http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com ,但我对尝试许多方法和功能感到非常沮丧.我的实际代码是这样的:

Hi everyone i'am fighting and searching solutions about this from 3 days. I have a problem getting data from sharethis.com RESTapi. I am working with jQuery and Laravel 5.2. I want to get values from this json: http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com but i'am very frustated trying a lot of methods and functions. My actual code is this:

function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
}
$.ajax({
url: 'http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com',
type: 'GET',
beforeSend: setHeader,
contentType: 'application/json; charset=utf-8',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});

此请求始终返回失败!".我对CORS的含义有些了解,但在实践中我无法使其正常工作.有任何想法吗?谢谢.

This request always return "Failed!". I understand a little what CORS means but on practice i can't make it work. Any ideas? Thanks..

推荐答案

也许您实际上不了解CORS:)

Maybe you actually don't understand CORS :)

这些标头必须出现在响应中,而不是请求中.

These headers have to be present in the response, not in the request.

服务器必须提供它们.

服务器必须同意.

您提供的URL没有CORS标头,因此除非您修改后端,否则您无法通过AJAX来获取它.

The URL you provided doesn't have CORS headers so you can't fetch it via AJAX unless you modify the backend.

这篇关于Ajax Jquery CORS无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆