纯JavaScript中的AJAX Post实现 [英] AJAX Post Implementation in Pure Javascript

查看:98
本文介绍了纯JavaScript中的AJAX Post实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在纯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?

推荐答案

是的,当然可以:)

<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对象并遍历每个元素的elements数组,并将它们的名称和值附加到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 Post实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆