Ajax sends data to the server

Source: Internet
Author: User
This article mainly introduces the Ajax advanced function of Ajax to the server to send data related information, the need for friends can refer to, hope to help everyone.

1. Preparing to send data to the server

One of the most common uses of Ajax is to send data to the server. The most typical scenario is sending form data from the client, which is the value entered by the user in each INPUT element contained in the form element. The following code shows a simple form:


<! DOCTYPE html>

The form in this example contains three input elements and a submit button. These input elements allow the user to specify three different types of words to order, and the button submits the form to the server.

1.1 Defining the server

It is obvious that the server that handles the request needs to be created for these examples. Again, node. JS is used here, mainly because it is simple and JavaScript is used. The new Fruitcalc.js script file is 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 (k, "OK", {"Content-type": "text/html", "Access-control-allow-origin": "http://localhost:63342"}); Res.write (' 

Highlight part of the script: Writeresponse function. This function is called after extracting the requested form value, which is responsible for producing a response to the browser. Currently, this function creates a simple HTML document with the following effect:

This response is simple, and the effect is to have the server calculate the total number of fruits ordered by the input elements in the form. The remainder of the server-side script is responsible for decoding the various possible data formats that the client sends with Ajax.

1.2 Understanding the problem

The above picture clearly describes the problem that you want to solve with Ajax.

When the form is submitted, the browser displays the results on the new page. This means two points:

* The user must wait for the server to process the data and generate a response;

* All document context information is missing because the result is displayed as a new document.

This is the ideal scenario for applying Ajax. Requests can be generated asynchronously so that users can continue to interact with the document when the form is processed.

2. Send the form

The most basic way to send data to a 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 way to use it:


<! DOCTYPE html>

As follows:

The HTML document returned by the server response form submission is displayed on the same page, and the request is executed asynchronously.

3. Sending JSON data

Ajax is used not only to send form data, but to send almost any data, including JavaScript Object Notation (Notation,json) data, which is almost a popular data format. Ajax is rooted in XML, but this format is cumbersome. When running a Web application that must transmit a large number of XML documents, the tedious meaning is the actual cost of bandwidth and system capacity.

JSON is often referred to as the "skim" alternative to XML. JSON is easy to read and write, is more compact than XML, and has gained extensive support. JSON originates from JavaScript, but it has evolved beyond JavaScript and is understood and used by countless packages and systems.

Here is an example of a simple JavaScript object that is expressed in JSON:


{"Bananas": "2", "Apples": "5", "Cherries": "20"}

This object has three properties: bananas, apples, and cherries. The values for these properties are 2, 5, and 20, respectively.

The functionality of JSON is not as rich as XML, but for many applications, those features are not available. JSON is simple, lightweight and expressive. The following example shows how simple it is to send the JSON data to the server, and the JavaScript part that modifies the previous one is 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 properties that correspond to the value of the Name property of each INPUT element within the form. You can use any data, but the input element is convenient and can be consistent with the previous example.

To tell the server that the JSON data is being sent, set the requested Content-type header to Application/json, like this:

Httprequest.setrequestheader ("Content-type", "Application/json");
The JSON object and JSON format are used to convert each other. (Most browsers can support this object directly, but you can also use the script in the following URL to add the same functionality to older browsers: https://github.com/douglascrockford/JSON-js/blob/master/ Json2.js) A JSON object provides two methods:

In the example above, the Stringify method is used and the result is passed to the XMLHttpRequest object's Send method. In this case, only the data encoding has changed. The effect of submitting the form is still the same.

4. Sending form data using the Formdata object

Another way to collect forms that are more concise is to use a Formdata object, which is defined in the second-level specification of XMLHttpRequest.

Because of the problem with the original node. JS code, here is a new file fruitcalc.aspx in C # as the server that handles the request. Its CS code is as follows:


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 < Request.Form.Count; i++) {Total + = Int32.Parse (Request.form[i]);}} Writeresponse (Response, total);}} private void Writeresponse (System.Web.HttpResponse Response, int total) {string strhtml; Response.AddHeader ("Access-control-allow-origin", "http://localhost:63342"); strhtml = Total + "Item ordered"; Response.Write (strhtml);}}}

4.1 Creating a FormData Object

When you create a Formdata object, you can pass a Htmlformelement object so that the values of all elements in the form are automatically collected. Examples are as follows:


<! DOCTYPE html>

The key change, of course, is the use of Formdata objects:


var formData = new FormData (form);

The other area to note is that the value of the Content-type header is no longer set. If you use the Formdata object, the data is always encoded as multipart/form-data. After submitting the form, the following example shows the effect:

4.2 Modifying Formdata objects

The Formdata object defines a method that allows you to add a name/value pair to the data to be sent to the server.

You can use the Append method to augment the data collected from the form, or you can create Formdata objects without using Htmlformelement. This means that you can use the Append method to choose which data values to send to the client. Modify the JavaScript code for 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 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>

In this script, the Htmlformelement object is not provided when the Formdata object is created. It then uses the DOM to find all the input elements in the document and adds a name/value pair to the element whose value is not cherries for the name attribute. After submitting the form, this example shows the following effect:

5. Sending files

You can use the Formdata object and the Type property to send a file to the server for the input element of file. When a form is submitted, the Formdata object automatically ensures that the file content selected by the user is uploaded with the other form values. The following example shows how to use the Formdata object in this way.


<! DOCTYPE html>

In this case, the most obvious change occurs on the form element. When the input element is added, the Formdata object uploads any file selected by the user.

Modify the Fruitcalc.aspx CS file as follows:


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.contentty Pe. IndexOf ("Multipart/form-data") >-1) {for (int i = 0; i < Request.Form.Count, i++) {total + = Int32.Parse (request.form[ I]);} if (request.files["file"]! = null) {Httppostedfile file = request.files["file"];file. SaveAs (Server.MapPath ("/upload/pictures/" + file). FileName));}} Writeresponse (Response, total);}} private void Writeresponse (System.Web.HttpResponse Response, int total) {string strhtml; Response.AddHeader ("Access-control-allow-origin", "http://localhost:63342"); strhtml = Total + "Item ordered"; Response.Write (strhtml);}}}

This example shows the following effect:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.