Ajax advanced functionality Ajax sends data to the server _ajax related

Source: Internet
Author: User
Tags require

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 to send 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>  

In this example, the form contains three input elements and a submit button. These input elements allow users to specify three different how many they want to order, and button to submit the form to the server.

1.1 Defining the server

Obviously, you need to create the server that handles the request for these examples. The main reason for using node.js again is that it's simple and uses JavaScript. 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 (ok
", {" Content-type ":" text/html "," Access-control-allow-origin ":" http://localhost:63342 "});
Res.write ('  

The highlighted part of the script: the Writeresponse function. This function is invoked 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:

The response is simple, and the effect is to have the server calculate the total number of fruits ordered by the user through each INPUT element 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 you submit a form, the browser displays the results on a new page. This means two points:

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

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

This is the ideal scenario for applying Ajax. The request can be generated asynchronously so that the user can continue to interact with the document while the form is being processed.

2. Send 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. That's the way it works:

<! DOCTYPE html>  

The effect chart is as follows:

The HTML document returned after the server responds to the form submission appears on the same page, and the request is executed asynchronously.

3. Send JSON data

Ajax is not only used to send form data, it can send almost any data, including JavaScript Object notation (JavaScript objects Notation,json) data, and it has almost become a popular data format. Ajax is rooted in XML, but this format is cumbersome. When a running Web application must transfer a large number of XML documents, cumbersome means 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 widespread support. JSON originated in JavaScript, but it has evolved beyond 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 for these properties are 2, 5, and 20, respectively.

JSON is not as rich as XML, but for many applications, the functionality is not available. JSON is simple, lightweight, and expressive. The following example shows how simple it is to send JSON data to a server, and the JavaScript portion of the previous revision 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 =) {
document.getElementById ("Results"). InnerHTML = Httprequest.responsetext;
}
</script>

This script creates a new object and defines attributes to correspond to the Name property values of each INPUT element in the form. You can use any data, but the input element is convenient and can be consistent with previous examples.

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

Httprequest.setrequestheader ("Content-type", "Application/json");
Convert between JSON objects and JSON formats. (Most browsers can support this object directly, but you can also add the same functionality to older browsers using the script in the URL below: https://github.com/douglascrockford/JSON-js/blob/master/ Json2.js) The JSON object provides two methods:

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

4. Send form data using the Formdata object

Another more concise form collection method is to use a Formdata object, which is defined in the secondary specification of XMLHttpRequest.

Since the original Node.js code is problematic, create a new file in C # fruitcalc.aspx 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 FormData Objects

A Htmlformelement object can be passed when the Formdata object is created 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 the Formdata object:

var formData = new FormData (form);

The other place to note is that the Content-type header value is no longer set. If you use the Formdata object, the data will always be encoded as multipart/form-data. After submitting the form, this example displays the following 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 add data collected from a form by using the Append method, 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 =) {
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 for those elements whose name attribute's value is not cherries. After submitting the form, this example displays the following effect:

5. Send the file

You can use the Formdata object and the Type property to send files to the server for the file's INPUT element. When a form is submitted, the Formdata object automatically ensures that the content of the file selected by the user is uploaded with 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 files that the user chooses.

The CS file to modify fruitcalc.aspx is 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.ContentType.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 effects:

The above is a small set to introduce Ajax advanced features Ajax to the server to send data, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.