https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

As in the previous article, HTML forms can send an HTTP request declaratively. But forms can also prepare an HTTP request to send via JavaScript. This article explores ways to do that.

A form is not always a form Section

With open Web apps, it's increasingly common to use HTML forms other than literal forms for humans to fill out — more and more developers are taking control over transmitting data.

Gaining control of the global interface Section

Standard HTML form submission loads the URL where the data was sent, which means the browser window navigates with a full page load. Avoiding a full page load can provide a smoother experience by hiding flickering and network lag.

Many modern UIs only use HTML forms to collect input from the user. When the user tries to send the data, the application takes control and transmits the data asynchronously in the background, updating only the parts of the UI that require changes.

Sending arbitrary data asynchronously is known as AJAX, which stands for "Asynchronous JavaScript And XML."

How is it different? Section

AJAX uses the XMLHttpRequest (XHR) DOM object. It can build HTTP requests, send them, and retrieve their results.

Note: Older AJAX techniques might not rely on XMLHttpRequest. For example, JSONP combined with the eval() function. It works, but it's not recommended because of serious security issues. The only reason to use this is for legacy browsers that lack support for XMLHttpRequest or JSON, but those are very old browsers indeed! Avoid such techniques.

Historically, XMLHttpRequest was designed to fetch and send XML as an exchange format. However, JSON superseded取代 XML and is overwhelmingly more common today.

But neither XML nor JSON fit into form data request encoding. Form data (application/x-www-form-urlencoded) is made of URL-encoded lists of key/value pairs. For transmitting binary data, the HTTP request is reshaped into multipart/form-data.

If you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send JSON/XML and process them however you want.

But if you want to use a third party service, it's not that easy. Some services only accept form data. There are also cases where it's simpler to use form data. If the data is key/value pairs, or raw binary data, existing back-end tools can handle it with no extra code required.

So how to send such data?

Sending form data Section

There are 3 ways to send form data, from legacy techniques to the newer FormData object. Let's look at them in detail.

1.Building an XMLHttpRequest manually

XMLHttpRequest is the safest and most reliable way to make HTTP requests. To send form data with XMLHttpRequest, prepare the data by URL-encoding it, and obey the specifics of form data requests.

Note: To learn more about XMLHttpRequest, these articles may interest you: An introductory article to AJAX and a more advanced tutorial about using XMLHttpRequest.

Let's rebuild our previous example:

<button type="button" onclick="sendData({test:'ok'})">Click Me!</button>

As you can see, the HTML hasn't really changed. However, the JavaScript is completely different:

function sendData(data) {
var XHR = new XMLHttpRequest();
var urlEncodedData = "";
var urlEncodedDataPairs = [];
var name; // Turn the data object into an array of URL-encoded key/value pairs.
for(name in data) {
urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
} // Combine the pairs into a single string and replace all %-encoded spaces to
// the '+' character; matches the behaviour of browser form submissions.
urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+'); // Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
}); // Define what happens in case of error
XHR.addEventListener('error', function(event) {
alert('Oops! Something goes wrong.');
}); // Set up our request
XHR.open('POST', 'https://example.com/cors.php'); // Add the required HTTP header for form data POST requests
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Finally, send our data.
XHR.send(urlEncodedData);
}

Note: This use of XMLHttpRequest is subject to the same origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control.

2.Using XMLHttpRequest and the FormData object Section

Building an HTTP request by hand can be overwhelming. Fortunately, a recent XMLHttpRequest specification provides a convenient and simpler way to handle form data requests with the FormData object.

The FormData object can be used to build form data for transmission, or to get the data within a form element to manage how it's sent. Note that FormData objects are "write only", which means you can change them, but not retrieve their contents.

Using this object is detailed in Using FormData Objects, but here are two examples:

3.Building a DOM in a hidden iframeSection

The oldest way to asynchronously send form data is building a form with the DOM API, then sending its data into a hidden <iframe>. To access the result of your submission, retrieve the content of the <iframe>.

Dealing with binary data Section

If you use a FormData object with a form that includes <input type="file"> widgets, the data will be processed automatically. But to send binary data by hand, there's extra work to do.

There are many sources for binary data on the modern Web: FileReader, Canvas, and WebRTC, for example. Unfortunately, some legacy browsers can't access binary data or require complicated workarounds. Those legacy cases are out of this article's scope. If you want to know more about the FileReader API, read Using files from web applications.

Sending binary data with support for FormData is straightfoward. Use the append() method and you're done. If you have to do it by hand, it's trickier.

In the following example, we use the FileReader API to access binary data and then build the multi-part form data request by hand:

Sending forms through JavaScript[form提交 form data]的更多相关文章

  1. Sending forms through JavaScript

    https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript As in the ...

  2. 怎么利用jquery.form 提交form

    说明:开发环境 vs2012 asp.net mvc c# 利用jQuery.form.js提交form 1.HTML前端代码 <%@ Page Language="C#" ...

  3. easyui form提交和formdata提交记录

    1  easyui form提交 $('form').form('submit',{ url:''; onSubmit:''; success:function(data){ //这种方法获取到的da ...

  4. Extjs ajax form 提交

    1.form 提交 form.form.submit({ url: "/HandlerExcelToDB/UploadFile.ashx", params: {}, success ...

  5. JavaScript模拟Form提交

    在一个系统跳转到另外一个系统中时,可以用WAS的全局安全性,也可以用共享session做单点登陆,这次接触到了js模拟form提交的方式. function loginOAForm(url) { va ...

  6. 【JavaScript】Html form 提交表单方式

    源:http://blog.csdn.net/wang02011/article/details/6299517 1.input[type='submit'] 2.input[type='image' ...

  7. JavaScript 创建一个 form 表单并提交

    <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...

  8. javascript form提交 不执行onsubmit事件解决方案

    转载自:https://www.cnblogs.com/lorgine/archive/2011/03/30/2000284.html 今天做项目过程中,需要用到javascript提交form到后台 ...

  9. AngularJS系列:表单全解(表单验证,radio必选,三级联动,check绑定,form提交验证)

    一.查看$scope -->寻找Form控制变量的位置 Form控制变量 格式:form的name属性.input的name属性.$... formName.inputField.$pristi ...

随机推荐

  1. 获取文件夹中前N个文件

    @echo off set input="list.txt" set srcDir="%1" set /a fileCount=10 set /a curInd ...

  2. 存储过程SET XACT_ABORT ON

    设置事务回滚的当为ON时,如果你存储中的某个地方出了问题,整个事务中的语句都会回滚为OFF时,只回滚错误的地方

  3. 配置Trunk接口

    实验内容 本实验模拟某公司网络场景.公司规模较大,员工200余名,内部网络是-一个大的局域网.公司放置了多台接入交换机(如S1和S2)负责员工的网络接入.接入交换机之间通过汇聚交换机S3相连.公司通过 ...

  4. [Python3] 018 if:我终于从分支中走出来了

    目录 0. 谁是主角 1. 从三大结构说起 (1) 顺序 (2) 分支 1) 分支的基本语法 2) 双向分支 3) 多路分支 (3) 循环 0. 谁是主角 分支是主角 我前面几篇随笔提到 if 不下2 ...

  5. Java设计模式——模板方法设计模式(abstract修饰)

    解释: 一个抽象类中,有一个主方法,再定义 1...n 个方法,可以是抽象的,也可以是实际的方法,定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用. 解决的问题: 当功能内部一 ...

  6. P1828 香甜的黄油 (spfa)

    [题目描述] 农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛).给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那). [题目链接] https ...

  7. Educational Codeforces Round 60 (Rated for Div. 2) D. Magic Gems(矩阵快速幂)

    题目传送门 题意: 一个魔法水晶可以分裂成m个水晶,求放满n个水晶的方案数(mol1e9+7) 思路: 线性dp,dp[i]=dp[i]+dp[i-m]; 由于n到1e18,所以要用到矩阵快速幂优化 ...

  8. EF添加关联的提示问题:映射从第 260 行开始的片段时有问题:

    一,EF添加关联的提示问题 严重性 代码 说明 项目 文件 行 禁止显示状态错误 错误 3004: 映射从第 260 行开始的片段时有问题:没有为 设置 T_xx_xxRelation 中的属性 T_ ...

  9. ansible组

    安装公钥:服务器互通需要公钥和秘钥 https://www.cnblogs.com/yaozhiqiang/p/9951606.html 配置完成pulic ssh key(公钥和秘钥)之后 进入/e ...

  10. python实现不同条件下单据体的颜色不一样,比如直接成本分析表中关闭的细目显示为黄色

    #引入clr运行库 import clr #添加对cloud插件开发的常用组件的引用 clr.AddReference('Kingdee.BOS') clr.AddReference('Kingdee ...