Graphics and Text analysis Ajax principles _ajax Related

Source: Internet
Author: User
Tags http request php code

First on schematic diagram:

Background:

1. Traditional Web sites, submitting forms, need to reload the entire page.

2. If the server fails to return response for a long time, the client will be unresponsive and the user experience is poor.

3. When the server returns to response, the browser needs to load the entire page, and the burden on the browser is great.

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

Problem:

1. How to improve?

What's 2.AJAX?

3. What are the advantages?

4. What are the drawbacks?

One, what is AJAX

1. Why Ajax is needed

When you need to get data from the server, and refresh the page operation, if not using AJAX, you need to submit the entire form, when submitting the form, send the request to the server, the page needs to wait for the server to send the response after the page can resume operation.

The concept of 2.AJAX:

1.AJAX = asynchronous JavaScript and XML.

2.AJAX is a technology for creating fast Dynamic Web pages.

3. The Web page can be asynchronously updated by a small amount of data exchanged in the background with the server.

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

3. What is called asynchronous

The current page sends a request to the server, and the current page does not need to wait for a response from the server to manipulate the page. After the request is sent, the current page can continue browsing and operation.

4. What is called local refresh

We can implement partial refreshes in two ways.

1. The way of the IFRAME page overload.

This approach, while implementing a partial refresh, is a page overload, so it can also cause performance problems.

Step1. Define an IFRAME in the page

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

Step2. Setting the src of the IFRAME

var indexframe = document.getElementById ("Indexframe");
INDEXFRAME.SRC = "introduction.php";

Step3. Add a button click event , when clicked this button, reset the iframe src, to achieve the page refresh inside the iframe. Content outside the 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 the function of a navigation bar:

    

  2.AJAX mode

Step1.javascrpit Send an asynchronous request

Step2. Server-side query database, return data

Step3. Service-Side return response

Step4. The client uses JavaScript to manipulate the DOM based on the returned response.

Look at the following example:

  

When we switch the item in DropDownList, JavaScript sends an asynchronous request to the server side, the server returns the data, and then JavaScript parses the data, splicing a table, and renders the table on the page.

Second, the principle of submitting form forms

1. Code

Client code:

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

Service-Side code:

public void ProcessRequest (HttpContext context)
{
  //delay for
  (int i = 0; i < 2; i++)
  {
   System. Threading.Thread.Sleep (1000);
  }
 
   Gets the value of the fname from the Requset.form. The prerequisite for using form to get 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";
 Writes a 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 and the page will refresh to show "Hello World Jackson0714"

5. After submitting form forms , the page sends the request and the service side returns the response process

6. By grasping the package , we can get the HTTP Headers

The browser sends HTTP to the server, and the protocol that is taken is the HTTP protocol.

In the process of transmission, we can look at the HTTP Headers.

Principles of AJAX submission requests and service responses

1. Code

Client-side 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 = =) {document.ge Telementbyid ("Mydiv"). InnerHTML = XMLhttp.responsetext; }
}

Here's one thing to be aware of.

var xmlhttp = createRequest(); 。

1. Allow the server to operate this variable, if defined as a local variable, the server can not assign values to XMLHTTP when it returns response. The callback function requires that the request be global in order to access the variable and its property values.

2. When defined as a global variable, there may be two requests or multiple requests sharing the same request object. This request object only holds a callback function to handle the server response. After the server returns two requested response, it is possible to invoke the callback function that is specified later. So there may be two completely different server responses that are handled by the same callback function, which may not be handled correctly. The workaround is to create two different request objects.

The service-side code does not change.

2. Enter "Jackson0714" and click the Sumbit button , the page will not refresh, display "Hello World Jackson0714" at the bottom

3.AJAX the process of sending requests and service-side return responses

4. By grasping the package, we can get the HTTP Headers

The browser sends HTTP to the server, and the protocol that is taken is the HTTP protocol.

In the process of transmission, we can look at the HTTP Headers:

5.AJAX Get and Post mode difference

The code for the AJAX send request and post send request is as follows:

Get method
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);
}
 
Post method
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);
 
}

Iv. Knowledge of XMLHttpRequest objects

Methods of 1.XMLHttpRequest objects

Properties of 2.XMLHttpRequest Objects

Five, jquery implementation Ajax

The following code implements when switching DropDownList item, triggers the Getweeklycalendar method, uses the JQuery class library method $.ajax to send the AJAX request.

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 the background successfully returns response, the Paintweeklycandler (data) method is executed

Background PHP Code

 <?php<br>//define the response format returned is the JSON-formatted header (' Content-type:text/json ');<
 Br>//Introduction of custom database connection files include ' dbconfig.php ';<br>//Introducing custom settings session files include_once ' session.php '; /* Function Requested by Ajax */if (isset ($_post[' func ')) &&!empty ($_post[' func ')) {switch ($_post[' func
       '] {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 = ', $mode = ') {//Logical code <br> <br> <br>
 Returns the response echo Json_encode (Array (' result ' => $DaysOfWeekResultsArray) in JSON format); }<br>?> 

Vi. Advantages

1. Use asynchronous way to communicate with the server, the page does not need to reload, the page does not refresh

2. On-demand data to reduce the burden on the server

3. Enables Web applications to respond more quickly to user interaction

4.AJAX is based on standardized and widely supported technologies that do not need to download browser plug-ins or applet, but require the client to allow JavaScript to execute on the browser

5. The content of the browser and the server-side code are separated. The contents of the page are all controlled by JavaScript, and the server is responsible for the logical checksum and taking data from the database.

Vii. shortcomings

1. Security issues: Exposing the service-side approach that hackers can use to attack

2. A large number of JS code, error prone

3.Ajax No refresh overload, because the page changes without refreshing the overload is so obvious, so it's easy for users to be bothered-users are not sure whether the current data is new or have been updated; Existing solutions are: in the relevant location hints, data updates of the area design more obvious, data updates to the user prompts, etc.

4. May damage the browser back button normal behavior;

5. Some handheld devices (such as mobile phones, pad, etc.) brought by the browser is not very good to support Ajax

Eight, the application scene

1. The scene of filtering and manipulating relevant data for data

2. Add/Remove tree node

3. Add/Remove a row of records in a list

4. Toggle Drop-down List Item

5. Verify the name of the registered username

Nine, does not apply the scene

1. Preservation of the entire page content

2. Navigation

Ten, summary

The above is the entire content of this article, the article is written in great detail, I hope to learn Ajax can help you oh.

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.