我在对我的服务器执行 AJAX 调用的函数中遇到非常奇怪的行为。
下面的代码取 self 的 jQuery 脚本。下面显示的 2 个函数在我的脚本中完全按照此顺序出现。如果您遵循警报,它们会记录整个脚本的处理顺序。
奇怪的、无法解释的、坦率地说对我的脚本过程来说有问题的是 $.ajax()
当我需要它时,调用没有被执行。它最后执行。
我的脚本编码有问题吗?
$(document).ready(function() {
$(window).load(function() {
$('#agentID').change(function() {
alert('This alert displays on screen First');
$.ajax({
url: '/scripts/ajaxAgent.php',
type: 'GET',
dataType: 'html',
data: 'lookup=' + $('#agentID').val(),
success: function(data) {
if (data == 1) {
alert('Oddly and incorrectly, this alert displays on screen Third');
$('.visibility').show();
$('#resTypeID').closest('div').removeClass("optional");
$('#resTypeID').closest('div').addClass("required");
}
else {
alert('Oddly and incorrectly, this alert displays on screen Third');
$('.visibility').hide();
$('#resTypeID').closest('div').removeClass("required");
$('#resTypeID').closest('div').addClass("optional");
}
resTypeVisibilityHandler = data; // this var is set to global at top of this script
}, // end success
error: function() {
alert('An error occurred in processing.');
} // end error
}); // end .ajax()
}); // end agentID .change()
$('#agentID').focus();
$(document).on('change', '.visibilityControl', function(event) {
alert('This alert displays on screen Second');
// ...
}); // end .on('change') visibility control
}); // end .load()
}); // end .ready()
@pep 找到了我独特问题的答案。由于某种原因,SO 阻止了新答案或错误答案。解决方案如下:
“因此,您可以简单地将脚本完成时需要执行的所有代码包装到一个函数中。然后,在 AJAX 成功结束时,您可以调用该函数,此时计时将是正确的,因为代码将按预期执行示例中的第三个。”
他明白了......这就是解决办法!
2014-12-12 @ 13:15 (GMT-5) 向 SO Lords 请求重开此问题,以便我能够正确接受正确答案。
最佳答案
Ajax 使用异步方式获取数据。现在,这意味着一旦发起数据请求,页面就会继续运行 javascript 的其余部分(如果可用),并在收到数据后运行 ajax 的 promise 。所以这完全取决于从 ajax URL 返回数据需要多长时间。在每种情况下,ajax promise 都会最后运行,因为浏览器中的脚本几乎立即运行,但从服务器获取数据需要更多时间。
关于javascript - 如何确保函数中的 jQuery 代码先于其他函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449417/