问题描述
在纯 Javascript 中是否有任何 AJAX Post 实现(可能使用 xmlhttprequest)?
is there any implementation of AJAX Post in Pure Javascript (maybe using xmlhttprequest)?
例如,如果我有这样的表格:
For example if I have a form like this:
<form action="request.php" id="register_form">
<input type="text" name="first_name" placeholder="First Name">
<input type="text" name="last_name" placeholder="LastName">
<input type="submit" value="submit_now">
</form>
这是我在 jQuery 中的 AJAX 实现
and this is my implementation of the AJAX in jQuery
$('#register_form').submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
/* start ajax submission process */
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
alert('Success!');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error occurred!');
}
});
e.preventDefault(); //STOP default action
/* ends ajax submission process */
});
我可以不使用 jQuery 做同样的事情吗?如果可能,如何将上述 jQuery 代码实现为纯/纯 Javascript 代码?
Can I do the same WITHOUT the use of jQuery? If it is possible, how can I implement the above jQuery code into pure/plain Javascript code?
推荐答案
是的,当然这是可能的:)
Yes and of course that's possible :)
<form action="request.php" id="register_form">
<input class='formVal' type="text" name="first_name" placeholder="First Name">
<input class='formVal' type="text" name="last_name" placeholder="LastName">
<input type="submit" value="submit_now" onclick="myFunction(); return false;">
</form>
JS
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData();
for(var i=0; i<elements.length; i++)
{
formData.append(elements[i].name, elements[i].value);
}
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("post", "server.php");
xmlHttp.send(formData);
}
server.php
<?php
$firstName = $_POST["first_name"];
$lastName = $_POST["last_name"];
echo $firstName." ".$lastName;
//enter name and lastname into your form and onclick they will be alerted
?>
解释:函数通过类名获取表单元素并将它们存储在数组中.然后我们创建 FormData 对象并循环遍历每个元素的元素数组,并将它们的名称和值附加到 FormData 对象.之后,我们创建 XMLHttpRequest() 对象来监控请求期间的状态和状态变化,并使用 post 方法将数据发送到 server.php当它结束并且readystate等于4并且status等于200时,我们警告来自server.php的响应,我们保存在XMLHttpRequest对象的responseText属性中.
Explanation: Function takes form elements by their class names and stores them in array. Then we create FormData object and loop through elements array for each element and append their name and value to FormData object. After that we create XMLHttpRequest() object that monitors state and status change during request and also sends data with post method to server.php When it's over and readystate equals to 4 and status equals to 200, we alert response from server.php, that we save in responseText attribute of XMLHttpRequest object.
这篇关于纯 Javascript 中的 AJAX 后期实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!