Principles of graph-text parsing AJAX, principles of graph-text parsing AJAX

Source: Internet
Author: User

Principles of graph-text parsing AJAX, principles of graph-text parsing AJAX

First, go to the schematic diagram:

 

 

 

Background:

1. for traditional websites, submitting forms requires reloading the entire page.

2. If the server fails to return Response for a long time, the client will not respond and the user experience will be poor.

3. After the server returns Response, the browser needs to load the entire page, which is also a great burden on the browser.

4. A large amount of data is sent after the browser submits a form, resulting in network performance problems.

Problem:

1. How to improve it?

2. What Is AJAX?

3. What are the advantages?

4. What are the disadvantages?

I. What is AJAX?

1. Why AJAX?

When you need to retrieve data from the server and refresh the page, if you do not use AJAX, You need to submit the entire form. When you submit a form, send a request to the server, the page can be restored only after the server sends the response.

2. AJAX concepts:

1. AJAX = Asynchronous JavaScript and XML.

2. AJAX is a technology used to create fast dynamic web pages.

3. The webpage can be asynchronously updated by performing a small amount of data exchange with the server in the background.

4. You can update a part of a webpage without reloading the entire webpage.

3. What is asynchronous?

The current page sends a request to the server. The current page does not need to wait for the server to respond to the operation. After sending the request, you can continue browsing the current page.

4. What is local refresh?

We can use two methods to partially refresh.

1. How to reload the iframe page.

This method implements partial refresh, but it is a page reload, so it will also bring performance problems.

Step1. define an Iframe in the page

<iframe id="indexFrame" name="index" width="1000" height="800"    frameborder="0" marginwidth="0" marginheight="0" scrolling="yes" style="margin-top:100px;"></iframe>

Step2. set the src of Iframe

var indexFrame = document.getElementById("indexFrame");indexFrame.src = "introduction.php";

Step3. Add a button click eventWhen you click this button, reset the src of Iframe to refresh the page in iframe. Content outside Iframe is not refreshed.

<button id="room" onclick='IndexClick("room")'>Click Me!</button>
function IndexClick(moduleKey) { var indexFrame = document.getElementById("indexFrame"); if(indexFrame == null) {   indexFrame = parent.document.getElementById("indexFrame"); } var url = "introduction.php"; switch (moduleKey) {  case "introduction":   url = "introduction.php";   break;  case "room":   url = "room.php";   break;  default:   {   } } indexFrame.src = url;}

In this way, we can implement a navigation bar function:

    

  2. AJAX

Step1.JavaScrpit sends an asynchronous request

Step2. the server queries the database and returns data

Step3. the server returns Response.

Step 4. The client uses JavaScript to operate the DOM Based on the returned Response.

See the following example:

  

When we switch the items in DropDownList, JavaScript sends an asynchronous request to the Server, and the Server returns the data. Then, JavaScript parses the data and concatenates a Table to display the Table on the page.

Ii. Principles of Form submission

1. Code

Client code:

<Form id = "form1" action = "Test. ashx "method =" get "> your name 1: <input type = "text" name = "fname" size = "20"/> <input type = "submit" name = "submit" value = "Sumbit"> </form>

Server code:

Public void ProcessRequest (HttpContext context) {// Delay for (int I = 0; I <2; I ++) {System. threading. thread. sleep (1000);} // from Requset. get the fname value in Form. The precondition for using Form to obtain the value of the requested key-value pair is that the HTTP request Content-Type value must be "application/x-www-form-urlencoded" or "multipart/form-data ". string fname = context. request ["fname"]; context. response. contentType = "text/plain"; // write the string to the HTTP Response output stream. Context. Response. Write ("Hello World" + fname );}

2. Deploy the code to IIS

3. Open the site:

Http: /localhost: 8003/Test.html

 

4. Enter Jackson0714 and click the Sumbit button.The page will be refreshed again, and "Hello World Jackson0714" will be displayed"

5. After submitting the FormThe process of sending a request on the page and returning a response from the server

6. Capture packets, We can get the HTTP Headers

The browser sends HTTP to the server. The protocol adopted is HTTP.

During transmission, we can look at HTTP Headers.

Iii. Principles of AJAX request submission and service response

1. Code

Client HTML code:

<! DOCTYPE html> 

Client JS Code:

var xmlhttp = createRequest(); function testGet() { var fname = document.getElementById("testGetName").value; xmlhttp.open("GET", "Test.ashx?fname=" + fname + "&random=" + Math.random() , true); xmlhttp.onreadystatechange = callback; xmlhttp.send(null);} function testPost() { var fname = document.getElementById("testPostName").value; xmlhttp.open("POST", "Test.ashx?" + "&random=" + Math.random() , true); xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.onreadystatechange = callback; xmlhttp.send("fname="+fname); } function createRequest() { var xmlhttp; if (window.XMLHttpRequest) {  // code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp = new XMLHttpRequest(); } else {  // code for IE6, IE5  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp} function callback() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {  document.getElementById("myDiv").innerHTML = xmlhttp.responseText; }}

Note that

var xmlhttp = createRequest(); 。

1. Enable the server to operate on this variable. If it is defined as a local variable, when the server returns response, it cannot assign values to the xmlhttp attribute. The callback function requires that the request be global to access this variable and its attribute values.

2. After being defined as a global variable, two or more requests may share the same request object. This request object can only store one callback function to process server responses. When the server returns two Response requests, it may call the callback function specified later. Therefore, two totally different server responses may be processed by the same callback function, which may not be correct. The solution is to create two different request objects.

The server code remains unchanged.

2. Enter "Jackson0714" and click "Sumbit ".The page will not be refreshed. "Hello World Jackson0714" is displayed at the bottom"

3. Process for sending AJAX requests and returning responses from the server

 

 

4. Through packet capture, we can get the HTTP Headers

The browser sends HTTP to the server. The protocol adopted is HTTP.

During transmission, we can look at HTTP Headers:

 

5. Differences between ajax get and POST Methods

The code for sending AJAX requests and POST requests is as follows:

// GET function testGet () {var fname = document. getElementById ("testGetName"). value; xmlhttp. open ("GET", "Test. ashx? Fname = "+ fname +" & random = "+ Math. random (), true); xmlhttp. onreadystatechange = callback; xmlhttp. send (null);} // function testPost () {var fname = document. getElementById ("testPostName "). value; xmlhttp. open ("POST", "Test. ashx? "+" & Random = "+ Math. random (), true); xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8"); xmlhttp. onreadystatechange = callback; xmlhttp. send ("fname =" + fname );}

4. XMLHttpRequest object knowledge

1. XMLHttpRequest object Method

2. attributes of the XMLHttpRequest object

V. AJAX implementation using JQuery

The following code triggers the getWeeklyCalendar method when the DropDownList item is switched. The JQuery class library method $. ajax is used to send AJAX requests.

Client JQuery code

function getWeeklyCalendar(name,currentDate,mode){ $.ajax({  type:'POST',  url:'weekProcess.php',data:'func=getWeeklyCalender&name='+name+'&currentDate='+currentDate+'& mode='+mode,  success:function(data){  paintWeeklyCandler(data);  } });}

After Response is returned successfully in the background, run the paintWeeklyCandler (data) method.

Background PHP code

<? Php <br> // defines the returned Response as a JSON header ('content-type: text/json '); <br> // introduce the custom database connection file include 'dbconfig. php '; <br> // introduce the custom session setting file include_once' session. php ';/** Function requested by Ajax */if (isset ($ _ POST ['function']) &! Empty ($ _ POST ['function']) {switch ($ _ POST ['function']) {case 'getweeklycalender ': getWeeklyCalender ($ _ POST ['name'], $ _ POST ['currentdate'], $ _ POST ['Mode']); break; case 'getweeklystatus ': getWeeklyStatus ($ _ POST ['name'], $ _ POST ['currentdate'], $ _ POST ['Mode']); break; case 'getevents ': getEvents ($ _ POST ['date'], $ _ POST ['name']); break; default: break;} function getWeeklyCalender ($ name = '', $ currentDate = '', $ mod E = '') {// logic Code <br> // return the Response echo json_encode (array ('result' => $ DaysOfWeekResultsArray) in JSON format ));} <br >?>

Vi. Advantages

1. Use asynchronous mode to communicate with the server. The page does not need to be reloaded, and the page does not need to be refreshed.

2. Retrieve data as needed to reduce the burden on the server

3. Make Web applications respond to user interaction more quickly

4. AJAX is based on standardized and widely supported technologies. You do not need to download browser plug-ins or applets, but you need to allow JavaScript to be executed on your browser.

5. the browser content is separated from the server code. All the page content is controlled by JAVAScript, and the server is responsible for logical checksum and data retrieval from the database.

VII. Disadvantages

1. Security Problem: expose the server method. Hackers can exploit this vulnerability to launch attacks.

2. A large number of JS code, which is prone to errors

3. ajax does not need to refresh new loads. Because the page changes are not as obvious as the refresh overload, it is easy for users to be troubled-users do not know whether the current data is new or updated; existing solutions include: the relevant location prompts, data update areas are designed to be obvious, and prompt users after data update.

4. The normal behavior of the browser's back button may be damaged;

5. Some browsers that come with handheld devices (such as mobile phones and tablets) cannot support Ajax yet.

8. application scenarios

1. Data Filtering and data manipulation scenarios

2. Add/delete Tree nodes

3. Add/delete a row of records in the list

4. Switch the drop-down list item

5. Verification of duplicate registered user names

9. inapplicable scenarios

1. Saving the entire page content

2. Navigation

10. Summary

The above is all the content of this article. The article is very detailed and I hope it will be helpful for you to learn about ajax.

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.