Javascript 在一个函数中使用CORS可变时间
我有一个需要身份验证的注册表单,它使用CORS go to文件执行SQL检查数据库,并返回身份验证密钥是否有效和未使用。 这是可行的,但我想对另一个文件执行一个附加的CORS请求,将密钥更改为used using SQL SQL非常简单,而且可以工作,我的问题是我不知道如何使用CORS两次,就像我使用 xhr.send() 它不会在函数中运行任何代码 以下是CORS功能:Javascript 在一个函数中使用CORS可变时间,javascript,jquery,ajax,cors,Javascript,Jquery,Ajax,Cors,我有一个需要身份验证的注册表单,它使用CORS go to文件执行SQL检查数据库,并返回身份验证密钥是否有效和未使用。 这是可行的,但我想对另一个文件执行一个附加的CORS请求,将密钥更改为used using SQL SQL非常简单,而且可以工作,我的问题是我不知道如何使用CORS两次,就像我使用 xhr.send() 它不会在函数中运行任何代码 以下是CORS功能: function createCORSRequest(method, url) { var xhr = new XM
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);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
这是我触发CORS的函数,它是一个点击,运行一个表单:
$('input[type=submit]', '#orm').on('click', function() {
let first = $('input[name="first"]', '#form').val();
var xhr = createCORSRequest("GET", "http://myurl.co.uk/keycheck?licensekey="+ authKey +"");
//This returns 1 if the code exists and is not set as used
xhr.onload = function() {
var result = xhr.responseText;
if(result == 1){
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
'action': 'install',
'authKey': authKey
},
success: function(data, status){
//The AJAX is a database install and file download, it works, and returns success
if(data = 'success'){
var downloaded = 1;
}
},
error: function(xhr, status, error){
//This doesn't happen, so ignore me
}
});
}else if(result == 2){
//here is where the message if your code was invalid come from
}
};
xhr.onerror = function() {
//This doesn't happen, so ignore me
};
xhr.send();
//it works up to this point and then just stops
if(downloaded == 1){
var xhr = createCORSRequest("GET", "http:///myurl.co.uk/keyused.php?licensekey="+ authKey +"");
xhr.onload = function() {
window.location.assign('../success.php');
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.send();
}
});
CORS工作一次,检查keycheck.php文件,但不检查keyuse.php文件
我的问题是如何在同一个函数中以不同的间隔执行CORS两次
提前谢谢 多亏了H.Figueiredo,问题解决了,问题是第二个请求的位置,但我的url有一个输入错误。如果(下载==1)您将永远无法输入
,因为该代码是在第一个AJAX调用完成之前执行的。我的建议是将if(downloaded==1)
的内容放在第一个AJAX调用的success函数中。或者,如果使用jQuery,则可以使用$.when
方法。要了解更多信息,请转到.@H.Figueiredo,我尝试了这个,但它console.logsXHR加载失败:GET“http://myurl.co.uk/keyused.php?licensekey=1111111111111111“
@H.Figueiredo我在xhr.onerror中为第二个验尸官请求添加了一个console.log,它将向何处移动。第一个请求仍在工作。@H.Figueiredo刚刚再试一次,它还说XMLHttpRequest无法加载http://myurl.co.uk/keyused.php?licensekey=1111111111111111. 请求的资源上不存在“Access Control Allow Origin”标头。起源'http://localhost因此,不允许访问。响应的HTTP状态代码为404。
keycheck.php上的头与keyuse.php上的头相同