Advanced Ajax functions-advanced ajax Functions

Source: Internet
Author: User

Advanced Ajax functions-advanced ajax Functions

1. Prepare to send data to the server

One of the most common uses of Ajax is to send data to the server. The most typical case is to send form data from the client, that 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 the order quantity of three different types, and the button will submit the form to the server.

1.1 define servers

Obviously, we need to create a server for processing requests for these examples. Here we use Node. js again, mainly because it is very 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(200,"OK",{"Content-Type":"text/html","Access-Control-Allow-Origin":"http://localhost:63342"});res.write('

Highlighted in the script: The writeResponse function. This function is called after the form value of the request is extracted. It is responsible for generating responses to the browser. Currently, this function creates a simple HTML document with the following effects:

This response is very simple. The result is that the server calculates the total number of fruits ordered by each input element in the form. The rest of the server's script is responsible for decoding various possible data formats sent by the client using Ajax.

1.2 understand the problem

The image above clearly describes the problem to be solved using Ajax.

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

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

* Context information of all documents is lost because the results are displayed as new documents.

This is the ideal situation for Ajax applications. Requests can be generated asynchronously, so that the user can continue to interact with the document when the form is processed.

2. Send a form

The most basic way to send data to the server is to collect and format it by yourself. The following code shows a script added to the preceding HTML document example.html. This method is used:

<! DOCTYPE html> 

As follows:

After the server responds to the form submission, the returned HTML document is displayed on the same page and the request is executed asynchronously.

3. Send JSON data

Ajax is not only used to send form data, but can send almost any data, including JavaScript Object Notation (JavaScript Object Notation, JSON) data. It has almost become a popular data format. Ajax is rooted in XML, but this format is cumbersome. When a running Web application must transmit a large number of XML documents, the complexity of the process means the actual cost of bandwidth and system capacity.

JSON is often referred to as an "Skim" alternative to XML. JSON is easier to read and write. It is more compact than XML and has been widely supported. 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 attributes: bananas, apples, and cherries. The values of these attributes are 2, 5, and 20.

JSON functions are not as rich as XML, but for many applications, those functions are not used. JSON is simple, lightweight, and expressive. The following example demonstrates how easy it is to send JSON data to the server. The JavaScript section for modifying the response 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 some attributes to correspond to the name attribute values of each input element in the form. You can use any data, but the input element is convenient and consistent with the previous example.

To tell the server that JSON data is being sent, set the request Content-Type header to application/json, as shown in the following code:

HttpRequest. setRequestHeader ("Content-Type", "application/json ");
Converts JSON objects to JSON format. (Most browsers can directly support this object, but you can also use the script in the following URL to add the same feature to the old browser: https://github.com/douglascrockford/JSON-js/blob/master/json2.js) The JSON object provides two methods:

In the preceding example, the stringify method is used and the result is passed to the send method of the XMLHttpRequest object. In this example, only the data encoding method has changed. The effect of submitting a form is the same.

4. Use the FormData object to send form data

Another more concise form collection method is to use a FormData object, which is defined in the second-level specification of XMLHttpRequest.

Because the original Node. js code is a bit problematic, here we use C # To create a new file fruitcalc. aspx as the server for processing requests. 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 create a FormData object

When creating a FormData object, you can pass an HTMLFormElement object so that the values of all elements in the form are automatically collected. Example:

<! DOCTYPE html> 

Of course, the key change is to use the FormData object:

var formData = new FormData(form);

Note that the Content-Type header value is no longer set. If the FormData object is used, the data is always encoded as multipart/form-data. In this example, after the form is submitted, the result is as follows:

4.2 modify the FormData object

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

You can use the append method to add the data collected from the form, or create a FormData object without using HTMLFormElement. This means you can use the append method to select the data values sent to the client. Modify the JavaScript code in 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. Then, use the DOM to find all the input elements in the document and add name/value pairs for those elements whose name attribute values are not cherries. In this example, after the form is submitted, the result is as follows:

5. Send files

You can use the FormData object and the input element whose type attribute is file to send files to the server. When a form is submitted, the FormData object automatically ensures that the content of the selected file is uploaded together with other form values. The following example shows how to use the FormData object in this way.

<! DOCTYPE html> 

In this example, the most obvious change occurs on the form element. After the input element is added, the FormData object uploads any file selected by the user.

Modify the cs file of fruitcalc. aspx 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);}}}

In this example, the result is as follows:

The above is the advanced Ajax function described in the editor. ajax sends data to the server. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.