我在CHROME中面临一个奇怪的错误。该代码在firefox中运行良好。
$.ajax({
url: someurl,
type: 'POST',
data: {},
headers: headers,
success: function(data) {
if (data.href) {
// create cookies
if (manager) {
window.location.href = "/index.html";
} else if (admin) {
window.location.href = "/admin.html";
} else {
window.location.href = "/tester.html";
}
}
},
error: function(data) {
$('#error').html("Invalid username or password.");
}
});
如果页面的url被更改为someurl/index.html,并且有大量的ajax调用比href立即更改,但在所有数据加载后页面被重定向到someurl/index.html
我发现了问题并想出了解决办法。
问题是异步ajax调用。在调用之前,我将async设置为false,并在调用之后将其设置为true。这在任何情况下都有效。
async = false;
$.ajax({
url: someurl,
type: 'POST',
data: {},
async : false,
headers: headers,
success: function(data) {
if (data.href) {
// create cookies
if (manager) {
window.location.href = "/index.html";
} else if (admin) {
window.location.href = "/admin.html";
} else {
window.location.href = "/tester.html";
}
}
},
error: function(data) {
$('#error').html("Invalid username or password.");
}
});
async = true;
像这样运行ajax调用
$(window).load(function() {
// ajax call
});