编辑 - 已解决。
谢谢大家花时间回复。经过数小时的研究后,我被引导到 CORS,但事实证明我应该一直在看 JSONP。我看了一些教程,我想我明白了。再次感谢。
我要做的是将用户输入从表单传递到我的服务器,这与表单所在的服务器不同。我不会把这篇文章写得太长,所以我会直接跳到代码上。
在以下 javascript 代码中,出于安全问题,我通过 tagName 获取元素,我不想在我的 html 表单中使用名称属性。然后,我将检索到的数据存储到 JSON 数据类型中,然后在其上调用 ajax 函数。
function processForm() {
var i, userInput, inputType;
var name, creditNo, cvv, month, year;
var inputs = document.getElementsByTagName("input");
for (i=0; i < inputs.length; i++){
inputType = inputs[i].getAttribute('data-tajer');
userInput = inputs[i].value;
if (inputType == 'name') {
name = userInput;
}
else if (inputType == 'cc') {
creditNo = userInput;
}
else if (inputType == 'cvv') {
cvv = userInput;
}
else if (inputType == 'month') {
month = userInput;
}
// year
else {
year = userInput
}
}
var myJASON = {"name": name, "cc": creditNo, "cvv": cvv, "month": month, "year": year};
var strJSON = JSON.stringify(myJASON);
ajaxCall(strJSON);
}
现在是ajax调用,这应该是微不足道的。这里唯一的区别是我的网址在不同的服务器上。
function ajaxCall(param){
var url = 'http://blahbalh';
// jquery code snippet
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Please update your browser biatch!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
else {
alert("failed");
}
}
ajaxRequest.open("POST", url, true);
// param is the JSON data.
ajaxRequest.send(param);
}
基本上现在发生的事情是我恢复了状态 0 和 readyState 1。你们能发现我做错了什么吗?请记住,我首先在 jQuery 中使用它,但它也不起作用。我愿意接受任何解决方案和建议。
为方便起见,我将提供 html 表单。
<form id="paymentForm">
<h3>Payment Form</h3>
<h4>Please fill in the form below, * are required fields.</h4>
<div>
<label>
<span>Name: *</span>
<input placeholder="Please enter your name as it appears on your credit card." id = "name" type="text" data-tajer="name" tabindex="1" required autofocus>
</label>
</div>
<div>
<label>
<span>Credit Card: *</span>
<input placeholder="Please enter credit card number" type="text" data-tajer="cc" tabindex="2" required>
</label>
</div>
<div>
<label>
<span>CVV: *</span>
<input placeholder="Please enter CVV code found on the back of your card" type="text" data-tajer="cvv" tabindex="3" required>
</label>
</div>
<div>
<label>
<span>Expiry Month: *</span>
<input placeholder="Please enter the expiry month of your credit card" type="text" data-tajer="month" tabindex="4" required>
</label>
</div>
<div>
<label>
<span>Expiry Year: *</span>
<input placeholder="Please enter expiry year of your credit card" type="text" data-tajer="year" tabindex="5" required></input>
</label>
</div>
<div>
<button onclick="processForm()">Process Payment</button>
</div>
</form>