Ajax 在检查器中响应正常,在 jquery 中不工作
Ajax response ok in inspector, not working in jquery
当我进行 Ajax 调用时,我可以在浏览器检查器中看到正确的响应值。但是,当我想在 js 中使用该响应时,我不能。
$(document).ready(function(){
$("button").click(function(){
var origin = "US";
var price = "277";
var currency = "AED";
var weight = "500";
var weightCurrency = "gram";
var count = 1;
$.ajax({
url: "http://www.zakoola.com/order/GetCalculatedPrice",
type: "Post",
data: { Origin: origin, Price: price, Currency: currency, Weight: weight, WeightCurrency: weightCurrency, Count: count }
})
.done(function (res) {
$("#price").html(res);
});
});
});
我在 html 中有一个 ID 为 #price
的 h1
标签。此外,我没有更改 h1
文本,而是尝试 alert()
显示 res
值,但它不起作用。似乎从未调用过响应函数,但我可以在检查器中看到响应值。
更新 1:
控制台显示正在调用 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.zakoola.com/order/GetCalculatedPrice. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
和 .fail
函数 return:{"readyState":0,"status":0,"statusText":"error"}
更新 2:只有 Firefox 正确显示响应负载。 Edge 和 IE 不是。
您正在使用 url: "http://www.zakoola.com/order/GetCalculatedPrice"
的 api 上的 CORS 似乎有问题,而不是 AJAX 故障。如果 api 方未指定来源(您的家 url),AJAX 将不允许请求继续。如果服务器 api 由您控制,您可以尝试在 api.
中设置所有需要的 CORS headers
考虑到更新,您应该在执行请求的服务器中添加 Access-Control-Allow-Origin
header。来自 MDN
The Access-Control-Allow-Origin response header indicates whether the
response can be shared with resources with the given origin.
其中 header 你应该设置你的原点 (http://example.com) 或 *
。
如果你不能修改后端 headers,你就不能以这种方式执行 ajax 请求。
关于浏览器兼容性见this,那么,你的Firefox可能低于3.5
当我进行 Ajax 调用时,我可以在浏览器检查器中看到正确的响应值。但是,当我想在 js 中使用该响应时,我不能。
$(document).ready(function(){
$("button").click(function(){
var origin = "US";
var price = "277";
var currency = "AED";
var weight = "500";
var weightCurrency = "gram";
var count = 1;
$.ajax({
url: "http://www.zakoola.com/order/GetCalculatedPrice",
type: "Post",
data: { Origin: origin, Price: price, Currency: currency, Weight: weight, WeightCurrency: weightCurrency, Count: count }
})
.done(function (res) {
$("#price").html(res);
});
});
});
我在 html 中有一个 ID 为 #price
的 h1
标签。此外,我没有更改 h1
文本,而是尝试 alert()
显示 res
值,但它不起作用。似乎从未调用过响应函数,但我可以在检查器中看到响应值。
更新 1:
控制台显示正在调用 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.zakoola.com/order/GetCalculatedPrice. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
和 .fail
函数 return:{"readyState":0,"status":0,"statusText":"error"}
更新 2:只有 Firefox 正确显示响应负载。 Edge 和 IE 不是。
您正在使用 url: "http://www.zakoola.com/order/GetCalculatedPrice"
的 api 上的 CORS 似乎有问题,而不是 AJAX 故障。如果 api 方未指定来源(您的家 url),AJAX 将不允许请求继续。如果服务器 api 由您控制,您可以尝试在 api.
考虑到更新,您应该在执行请求的服务器中添加 Access-Control-Allow-Origin
header。来自 MDN
The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.
其中 header 你应该设置你的原点 (http://example.com) 或 *
。
如果你不能修改后端 headers,你就不能以这种方式执行 ajax 请求。
关于浏览器兼容性见this,那么,你的Firefox可能低于3.5