我有一个非常简单的函数,旨在获取表单数据并通过CORS请求发送它。基本上是这样的…
window.onbeforeunload = function() {
formData = getFormData();
logAbandonment(formData);
// return formData;
// alert(formData);
}
function logAbandonment(formData)
{
if(!cors_request) {
cors_request = true;
} else {
return;
}
var url = 'http://mydomain.lan/sub/index.php';
var xhr = createCORSRequest('POST', url);
if (!xhr) {
console.log('Error: CORS not supported.');
}
xhr.send(formData);
}
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.onprogress = function () { };
xhr.ontimeout = function () { };
xhr.onerror = function () { };
xhr.onload = function() { };
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
function getFormData()
{
if(typeof FormData == 'undefined') {
return serialize(document.getElementById('AppForm'));
} else {
return new FormData(document.getElementById('AppForm'));
}
}
因为这是IE9我正在工作,我使用XDomainRequest javascript对象。
它成功地触发了ajax请求,但这里是我遇到问题的地方。它在不发送formData的情况下触发它,除非我取消返回行或警告行中的任何一行的注释,在这种情况下,它可以完美地工作。当我这样做的时候,我可以看到它应该在警告中说的正确数据。
我注意到的另一件事是,这只发生在我关闭浏览器或关闭选项卡时。如果我刷新页面,它就会像我想要的那样工作。
我想也许IE9在请求完成之前有一些奇怪的方法来破坏dom,但不幸的是,我找不到一种方法来将这个设置为XDomainRequest上的async false。
我也试过设置一个超时,但这似乎完全打破了它。
不是一个答案,而是一个解决方案,但我发现当调用xdr的open方法时,将查询字符串附加到url的末尾时,它可以完美地工作。