【发布时间】:2016-06-07 18:59:39
【问题描述】:
我正在尝试在 javascript 中发出 cors 请求。这是我的代码:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
但我无法收到请求。当我查看控制台时,http://127.0.0.1:8000/admin/managebadge/otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx 404(未找到)。如何删除模板中的“http://127.0.0.1:8000/admin/managebadge”(网址前缀)?我用 django。谢谢。
【问题讨论】:
-
我能问一下您为什么要使用获取请求来获取密码吗?除此之外,不清楚您要解决的问题是什么
-
@Sayse url 是一个 API。支持 GET 和 POST 方法。当我执行 makeCorsRequest() 时,没有显示警报。然后我检查元素控制台选项卡,有一个错误,我请求的 url 仍然包含前缀“127.0.0.1:8000/admin/managebadge”。我想删除那个前缀。谢谢。
-
你是在js中指定完整的URL:
var url = 'http://otherdomain.ashx?username=xxx&password=xxx&sportsBook=xxx&sportsType=xxx&gameType=xxx';吗? -
@doru 是的,这是完整的网址
标签: javascript django django-templates