当用户单击某个链接时,我想运行一个设置 $_SESSION
变量的 AJAX 调用,同时仍将用户引导至链接的 href
.
当我运行下面的代码时,Firebug 显示有错误,但没有指明; readyState=0, status=0, statusText="error"
是我从 console.log
得到的全部信息。
如果我将 e.preventDefault
和 window.location.href = linkPath;
添加到我的 success
函数中,脚本会将用户发送到正确的地方;但只有在等待 php 页面完成的延迟之后。
如何在运行 AJAX 调用的同时仍将用户毫不延迟地传递到他们的链接?
$(document).ready(function() {
$(".example_class").click(function(e) {
//Stop the page from leaving until we start our ajax
//e.preventDefault();
//var linkPath = this.href;
var form_data = new Object();
//Set the application ID for insert into the DB
form_data.variableName = encodeURIComponent('ExampleName');
//Send the data out to be processed and stored
$.ajax({
url:'/mypath/myfile.php',
type:'POST',
data:form_data,
success:function(return_data){
//window.location.href = linkPath;
return;
},
error:function(w,t,f){
console.log(w);
return;
}
});
return;
});
});
最佳答案
正如评论中所述,ajax 调用在调用者页面卸载时中止。 但是不代表服务器没有接到调用,只代表服务器还没有发回回复。 为了最大程度地减少 ajax 调用所花费的时间,您可以等待使用“xhr.onprogress”(未在 jquery 的 $.ajax 中实现)对 ajax 调用的第一个响应,然后打开链接。
但是,如果您控制了服务器,只需将 '/mypath/myfile.php?redirect_url='+linkPath 重定向到 linkPath 即可:
header('location: '.$_GET['redirect_url']);
关于javascript - 通过 AJAX onclick 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13299052/