jQuery 跨域jquery获取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15369577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cross domain jquery get
提问by Ajouve
I saw some examples of cross domain with ajax but it doesn't work.
我看到了一些使用 ajax 的跨域示例,但它不起作用。
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript" >
$(document).ready(function () {
var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1";
$.get(url, function (data) {
console.log(data)
alert(data);
});
});
</script>
</body>
</html>
I try on chrome and the following error is given:
我在 chrome 上尝试并给出以下错误:
XMLHttpRequest cannot load http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AssasNet&include_rts=1. Origin null is not allowed by Access-Control-Allow-Origin.
回答by T.J. Crowder
You can't use $.get
because that does an ajax call, which will be cross-origin and thus blocked by the Same Origin Policy, and the Twitter API you're trying to access doesn't support Cross-Origin Resource Sharing(or if it does, it doesn't allow either origin null
or http://jsbin.com
, which is the one I tried).
您不能使用,$.get
因为它执行了 ajax 调用,这将是跨域的,因此被Same Origin Policy阻止,并且您尝试访问的 Twitter API 不支持跨域资源共享(或者如果它确实,它不允许 originnull
或http://jsbin.com
,这是我尝试过的)。
The API does support JSONP(which is not a true ajax call), though, so just changing the $.get
to an $.ajax
specifying JSONP
works:
不过,API 确实支持JSONP(这不是真正的 ajax 调用),因此只需将 更改$.get
为$.ajax
指定即可JSONP
:
$.ajax({
url: url,
dataType: "jsonp",
success: function (data) {
console.log(data)
alert(data);
}
});