纯 Javascript 中的 AJAX 后期实现

AJAX Post Implementation in Pure Javascript(纯 Javascript 中的 AJAX 后期实现)
本文介绍了纯 Javascript 中的 AJAX 后期实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在纯 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 后期实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
How do I get the HTTP status code with jQuery?(如何使用 jQuery 获取 HTTP 状态码?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)