【发布时间】:2014-12-09 13:42:13
【问题描述】:
我正在尝试从外部 api 获取数据,但是 我不断收到错误消息:
XMLHttpRequest 无法加载...请求的资源上没有“Access-Control-Allow-Origin”标头。
这是我的代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
(function () {
$.support.cors = true;
$.ajax({
type: "GET", url: "http://zhettoapi.azurewebsites.net/api/Values?product=Coca Cola", success: function (data) {
window.alert("" + data);
//example of setting innerHTML of object
document.getElementById("myElement").innerHTML = "The number is:" + data;
}, error: function (xhr, status, error) {
// Display a generic error for now.
alert("Error: " + xhr + " " + status + " " + error);
}
});
})();
</script>
</head>
<body>
<div id="myElement"></div>
</body>
</html>
【问题讨论】:
-
错误告诉您确切的问题。该站点不允许您进行跨域调用。 developer.mozilla.org/en-US/docs/Web/Security/…
-
检查,如果那个api提供
JSONP请求,然后使用它,它支持CORS。 - stackoverflow.com/questions/5943630/…
标签: javascript ajax html azure asp.net-web-api