【发布时间】:2017-06-29 11:29:34
【问题描述】:
我只是不明白为什么我的 AJAX 不起作用。除了那个之外,每个 AJAX 请求都在我的网站上工作。正如我的错误代码所说,它“认为”我想要 AJAX 另一个域。
错误代码:
XMLHttpRequest 无法加载 https://www.example.com/。回应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。原点 'https://subdomain.example.com' 因此不是 允许访问。
我正在处理一个子域,而我想要 AJAX 的页面位于同一个子域上。比如我想AJAX subdomain.example.com/get-this from subdomain.example.com/from-here,我的subdomain.example.com/scripts/someting.js。
我的 JS 代码:
function ButtonClick() {
var amount;
$(document).on('immediately', '#amount', function () {
amount = $(this).val();
});
$("#amount").trigger('immediately');
$.ajax("get-this.cshtml",
{
data: { operation: "add", username: $("#uname").val(), productName: $("#show-box > div > i").first().text(), amount: amount },
success: function (response) {
if(response == "True")
{
alert();
}
else
{
alert("false");
}
},
error: function (request) {
alert(amount);
$("#error-div").text("Connection error, please try again.");
$("#error-div").fadeIn("fast");
setTimeout(function () {
$("#error-div").fadeOut("fast");
}, 1000);
}
});
setTimeout(Close , 1000); }
我不知道出了什么问题,datasection 中的每个值都是有效的(我检查过)并且异步没有问题。请有人解释一下发生了什么。
【问题讨论】:
-
出现这个错误是因为您正在向另一个域发送 ajax 请求
-
在 web.config 上,您可以在
<customHeaders>中使用<add name="Access-Control-Allow-Origin" value="*" /> -
你试过设置完整的网址吗?
-
您使用什么数据类型来响应?
-
我在同一个域和子域中工作。我还尝试编写完整的 URL 并得到这样的链接:
subdomain.example.com/subdomain.example.com/get-this此外,在我的另一个中我使用Response.Wrtie(true),将响应作为字符串处理并且它工作得很好......我真的不知道问题是什么。
标签: javascript jquery ajax iis