


Detailed explanation of the steps for sending data types to the server using ajax
This time I will bring you a detailed explanation of the steps for sending ajax to the serverdata type, what are the notes for ajax to send the data type to the server, the following is a practical case, let’s take a look take a look.
1. Prepare to send data to the server
The most common use of Ajax is to send data to the server. The most typical situation is to send form data from the client, that is, the values entered by the user in each input element contained in the form element. The following code shows a simple form:
nbsp;html> <meta> <title>基本表单</title> <style> .table{display: table;} .row{display: table-row;} .cell{display: table-cell;padding: 5px;} .lable{text-align: right;} </style>
The form in this example contains three input elements and a submit button. These input elements allow the user to specify the amount of each of three different orders, and the button will submit the form to the server.
1.1 Define the server
Obviously, you need to create the server that handles the requests for these examples. Node.js is used here again, mainly because it is simple and uses Javascript. Create a new fruitcalc.js script file as follows:
var http = require('http'); var querystring = require('querystring'); function writeResponse(res,data){ var total = 0; for(fruit in data){ total += Number(data[fruit]); } res.writeHead(200,"OK",{ "Content-Type":"text/html", "Access-Control-Allow-Origin":"http://localhost:63342" }); res.write('<title>Fruit Total</title>'); res.write('<p>'+total+' item ordered</p>'); res.end(); } http.createServer(function(req,res){ console.log("[200] "+req.method+" to "+req.url); if(req.method == "OPTIONS"){ res.writeHead(200,"OK",{ "Access-Control-Allow-Header":"Content-Type", "Access-Control-Allow-Methods":"*", "Access-Control-Allow-Origin":"*" }); res.end(); }else if(req.url == '/form'&& req.method == 'POST'){ var dataObj = new Object(); var contentType = req.headers["content-type"]; var fullBody = ''; if(contentType){ if(contentType.indexOf("application/x-www-form-urlencode") > -1){ req.on('data',function(chunk){ fullBody += chunk.toString(); }); req.on('end',function(){ var dBody = querystring.parse(fullBody); dataObj.apples = dBody["apples"]; dataObj.bananas = dBody["bananas"]; dataObj.cherries = dBody["cherries"]; writeResponse(res,dataObj); }); }else if(contentType.indexOf("application/json") > -1){ req.on('data',function(chunk){ fullBody += chunk.toString(); }); req.on('end',function(){ dataObj = JSON.parse(fullBody); writeResponse(res,dataObj); }); } } } }).listen(8080);
The highlighted part in the script: writeResponse function. This function is called after extracting the requested form values and is responsible for producing the response to the browser. Currently, this function creates a simple HTML document, with the following effect:
This response is very simple, and the effect is to let the server calculate what the user has done through each input element in the form. The total number of fruits ordered. The rest of the server-side script is responsible for decoding the various possible data formats sent by the client using Ajax.
1.2 Understand the problem
The above picture clearly describes the problem you want to solve with Ajax.
After submitting the form, the browser will display the results on a new page. This means two things:
* The user must wait for the server to process the data and generate a response;
* All document context information is lost because the result is displayed as a new document.
This is the ideal situation for applying Ajax. Requests can be generated asynchronously, allowing the user to continue interacting with the document while the form is being processed.
2. Send a form
#The most basic way to send data to the server is to collect and format it yourself. The following code shows a script added to the previous HTML document example.html. This is the method used:
nbsp;html> <meta> <title>手动收集和发送数据</title> <style> .table{display: table;} .row{display: table-row;} .cell{display: table-cell;padding: 5px;} .lable{text-align: right;} </style><script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ //对表单里的button元素而言,其默认行为是用常规的非Ajax方式提交表单。这里不想让他发生,所以调用了preventDefault方法 e.preventDefault(); var form = document.getElementById("fruitform"); //收集并格式化各个input的值 var formData =""; var inputElements = document.getElementsByTagName("input"); for (var i = 0; i < inputElements.length; i++){ formData += inputElements[i].name + "=" + inputElements[i].value +"&"; } httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; //数据必须通过POST方法发送给服务器,并读取了HTMLFormElement的action属性获得了请求需要发送的URL httpRequest.open("POST",form.action); //添加标头来告诉服务器准备接受的数据格式 httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //把想要发送给服务器的字符串作为参数传递给send方法 httpRequest.send(formData); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script>
The rendering is as follows:
The HTML document returned by the server after the form is submitted will be displayed on the same page, and the Requests are executed asynchronously.
3. Send JSON data
Ajax is not only used to send form data, but can send almost any data, including JavaScript objectsNotation (JavaScript Object Notation, JSON) data, and it has almost become a popular data format. Ajax has its roots in XML, but this format is cumbersome. When running web applications that must transmit large numbers of XML documents, the complexity means real costs in terms of bandwidth and system capacity.
JSON is often referred to as the "skim" alternative to XML. JSON is easy to read and write, more compact than XML, and already has widespread support. JSON originated from JavaScript, but its development has surpassed JavaScript and is understood and used by countless packages and systems.
The following is an example of a simple JavaScript object expressed in JSON:
{"bananas":"2","apples":"5","cherries":"20"}
This object has three properties: bananas, apples and cherries. The values of these properties are 2, 5, and 20 respectively.
JSON is not as feature-rich as XML, but for many applications, those features are not needed. JSON is simple, lightweight and expressive. The following example demonstrates how simple it is to send JSON data to the server. Modify the JavaScript part of the previous example as follows:
<script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ e.preventDefault(); var form = document.getElementById("fruitform"); var formData = new Object(); var inputElements = document.getElementsByTagName("input"); for(var i=0;i<inputElements.length;i++){ formData[inputElements[i].name] = inputElements[i].value; } httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open("POST",form.action); httpRequest.setRequestHeader("Content-Type","application/json"); httpRequest.send(JSON.stringify(formData)); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script>
This script creates a new Object and defines some attributes to correspond to each input element in the form. The name attribute value. You can use any data, but the input element is convenient and consistent with the previous example.
为了告诉服务器正在发送JSON数据,把请求的Content-Type标头设为 application/json,就像这样:
httpRequest.setRequestHeader("Content-Type","application/json");
用JSON对象和JSON格式进行相互的转换。(大多数浏览器能直接支持这个对象,但也可以用下面的网址里的脚本来给旧版的浏览器添加同样的功能:https://github.com/douglascrockford/JSON-js/blob/master/json2.js )JSON对象提供了两个方法:
在上面的例子中,使用了stringify方法,然后把结果传递给XMLHttpRequest 对象的send方法。此例中只有数据的编码方式发生了变化。提交表单的效果还是一样。
4. 使用FormData对象发送表单数据
另一种更简洁的表单收集方式是使用一个FormData对象,它是在XMLHttpRequest的第二级规范中定义的。
由于原来的Node.js代码有点问题,此处用C#新建文件 fruitcalc.aspx作为处理请求的服务器。其cs代码如下:
using System; namespace Web4Luka.Web.ajax.html5 { public partial class fruitcalc : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int total = 0; if (Request.HttpMethod == "POST") { if (Request.ContentType.IndexOf("multipart/form-data") > -1) { for (int i = 0; i <p style="text-align: left;"><strong>4.1 创建 FormData 对象</strong></p><p style="text-align: left;">创建FormData对象时可以传递一个HTMLFormElement对象,这样表单里所有的元素的值都会被自动收集起来。示例如下:</p><pre class="brush:php;toolbar:false">nbsp;html> <meta> <title>使用FormData对象</title> <style> .row{display: table-row;} .cell{display: table-cell;padding: 5px;} .lable{text-align: right;} </style><script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ e.preventDefault(); var form = document.getElementById("fruitform"); var formData = new FormData(form); httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open("POST",form.action); httpRequest.send(formData); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script>
当然,关键的变化是使用了FormData对象:
var formData = new FormData(form);
其他需要注意的地方是不再设置Content-Type标头的值了。如果使用FormData对象,数据总是会被编码为multipart/form-data 。本例提交表单后,显示效果如下:
4.2 修改FormData对象
FormData对象定义了一个方法,它允许给要发送到服务器的数据添加名称/值对。
可以用append方法增补从表单中收集的数据,也可以在不使用HTMLFormElement的情况下创建FormData对象。这就意味着可以使用append方法来选择向客户端发送哪些数据值。修改上一示例的JavaScript代码如下:
<script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ e.preventDefault(); var form = document.getElementById("fruitform"); var formData = new FormData(); var inputElements = document.getElementsByTagName("input"); for(var i=0;i<inputElements.length;i++){ if(inputElements[i].name != "cherries"){ formData.append(inputElements[i].name,inputElements[i].value); } } httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open("POST",form.action); httpRequest.send(formData); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script>
此段脚本里,创建FormData对象时并没有提供HTMLFormElement对象。随后用DOM找到文档里所有的input元素,并为那些name属性的值不是cherries的元素添加名称/值对。此例提交表单后,显示效果如下:
5. 发送文件
可以使用FormData 对象和type 属性为 file 的input 元素向服务器发送文件。当表单提交时,FormData对象会自动确保用户选择的文件内容与其他的表单值一同上传。下面的例子展示了如何以这种方式使用FormData对象。
nbsp;html> <meta> <title>使用FormData对象发送文件到服务器</title> <style> .row{display: table-row;} .cell{display: table-cell;padding: 5px;} .lable{text-align: right;} </style><script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ e.preventDefault(); var form = document.getElementById("fruitform"); var formData = new FormData(form); httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open("POST",form.action); httpRequest.send(formData); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script>
此例里,最明显的变化发生在 form元素上。添加了input元素后,FormData对象就会上传用户所选的任意文件。
修改 fruitcalc.aspx 的cs文件如下:
using System; using System.Web; namespace Web4Luka.Web.ajax.html5 { public partial class fruitcalc : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int total = 0; if (Request.HttpMethod == "POST") { if (Request.ContentType.IndexOf("multipart/form-data") > -1) { for (int i = 0; i <p style="text-align: left;">此例的显示效果如下:</p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/07ac3273710bffe203d470c5a98aaf80-6.gif?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p><p>推荐阅读:</p><p style="max-width:90%"><a href="http://www.php.cn/js-tutorial-391430.html" target="_blank">Ajax+mysq实现省市区三级联动列表</a></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-391428.html" target="_blank">Ajax表单提交及后台处理</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-391424.html" target="_blank">ajax怎么实现图片的预览上传以及查看缩略图</a><br></p>
The above is the detailed content of Detailed explanation of the steps for sending data types to the server using ajax. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor