如何使用没有 jQuery 但纯 Javascript 的 AJAX 提交此表单
Posted
技术标签:
【中文标题】如何使用没有 jQuery 但纯 Javascript 的 AJAX 提交此表单【英文标题】:How to submit this form using AJAX without jQuery but pure Javascript 【发布时间】:2014-03-20 01:08:39 【问题描述】:我翻遍了所有我能找到的都是关于 jQuery 的。
在 SO 的优秀人才的大力帮助下,我终于完成了我的表单验证(现在只是客户端,但那是因为它是一项任务)。我现在需要使用 AJAX 将表单提交到 php 文件。
我的要求是验证它是通过 AJAX 调用的,验证所有必填字段都有值并返回成功状态,包括处理它的服务器时间。
JSfiddle
表单操作现在是空的,用于测试,但最终会使用下面的代码调用 form.php。
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
JS
function validateFormOnSubmit(contact)
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
console.log(reason);
if (reason.length > 0)
return false;
else
return false;
// validate required fields
function validateName(name)
var error = "";
if (name.value.length == 0)
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
else
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
return error;
// validate email as required field and format
function trim(s)
return s.replace(/^\s+|\s+$/, '');
function validateEmail(email)
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "")
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
else if (!emailFilter.test(temail)) //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
else if (email.value.match(illegalChars))
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
else
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
return error;
// validate phone for required and format
function validatePhone(phone)
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "")
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
else if (isNaN(parseInt(stripped)))
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
else if (stripped.length < 10)
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
else
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
return error;
function validatePet(pet)
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false))
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
else
document.getElementById('pet-error').innerHTML = '';
return error;
function validateNumber(number)
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y))
//alert('va');
if (y < 0 || y > 50)
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
else
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
return error;
else
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
return error;
function validateDisclaimer(disclaimer)
var error = "";
if (document.getElementById("disclaimer").checked === false)
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
else
document.getElementById('disclaimer-error').innerHTML = '';
return error;
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$from = 'From: TangledDemo';
$to = 'myemail@domain.com';
$subject = 'Hello';
$message = "This is a message.";
if ($_POST['submit'])
if (mail ($to, $subject, $message))
echo '<p>Your message has been sent!</p>';
else
echo '<p>Something went wrong, go back and try again!</p>';
?>
谢谢!
【问题讨论】:
你不想使用jQuery有什么原因吗? @Nunners 可能由作业定义,正确的@justinae? @BillyMathews 我没注意到这是作业,我的坏哈哈 我想说“也许他不想包含任何库”或“也许他只是喜欢纯 JS”,看到I prefer
dogs
, cats
, @ 987654328@ 单选按钮我感觉不是这样
@BillyMathews 正确!
【参考方案1】:
您可以通过以下方式通过Ajax
提交表单:
function submitFormAjax()
let xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
if (this.readyState === 4 && this.status === 200)
alert(this.responseText); // Here is the response
let name = document.getElementById('name').innerHTML;
let email = document.getElementById('email').innerHTML;
xmlhttp.open("GET","your_url.php?name=" + name + "&email=" + email, true);
xmlhttp.send();
此示例使用GET
,但您也可以使用POST
:
xmlhttp.open("POST","your_url.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=" + name + "&email=" + email);
注意:
您必须在validateFormOnSubmit
正确完成后调用submitFormAjax()
,此处:
if (reason.length == 0)
// Show some loading image and submit form
submitFormAjax();
else
return false;
【讨论】:
好的@BillyMathews!不知道...我已经删除了参考:) @ToniAlmeida 谢谢。我现在开始测试它。我需要添加'var name = document.getElementById('name').innerHTML;'对于我要提交的每个字段还是仅需要提交的字段?那么这里发生的事情的要点是 ValidateForm 首先运行,排除所有错误,然后 submitForAjax 运行并基本上将整个表单提交到 form.php 而无需刷新页面?我仍然对 AJAX 感到困惑。 BillyMathews 我不知道 W3schools。感谢您的提醒。 在哪里可以测试 AJAX 还是必须在我的实时服务器上进行测试? @justinae,没错,首先你验证一切,然后,你提交带有所有需要参数的表单!而 AJAX 允许您在不刷新页面的情况下执行此操作! 您不需要,只需将每个值添加为 getxmlhttp.open("GET" ...
的参数(除非您的页面中有多个表单,对吗?)【参考方案2】:
在现代浏览器中,您只需几行即可使用fetch
:
fetch(form.action,
method: form.method,
body: new URLSearchParams(new FormData(form)),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
);
如果您不喜欢从 *** 复制粘贴代码,我还发布了一个稍微复杂的版本作为 npm 包:push-form
【讨论】:
【参考方案3】:formElem.onsubmit = async (e) =>
var url = document.getElementById("formElem").getAttribute("action");
e.preventDefault();
var data = new FormData(formElem);
data.append("submit", "Submit");
let response = await fetch(url,
method: 'POST',
body: data
);
let result = await response.json();
document.getElementById("field").value = "";
document.getElementById('charNum').innerHTML="0";
setTimeout(function autoscroll()
var div = document.getElementById('loadmsg');
div.scrollTop = div.scrollHeight - div.clientHeight;
,1000);
;
【讨论】:
以上是关于如何使用没有 jQuery 但纯 Javascript 的 AJAX 提交此表单的主要内容,如果未能解决你的问题,请参考以下文章
JQuery:通过noConflict()方法同时使用jQuery 和其他框架
没有 jquery 的 Django CSRF 丢失或不正确的 Ajax POST (Vanilla JavaScript)