Ajax is undoubtedly one of the hottest web development technologies fired in 2005.Of course, this credit cannot be separated from Google. I am just a regular developer,There are not many places to use ajax,I will simply talk about my experience.(This article assumes that users already have basic web development capabilities such as javascript, html, css)

[ajax introduction]Ajax is a web application development method that uses client script to exchange data with a web server.The web page does not need to interrupt the interactive process for re-cutting.It can be updated dynamically.With ajax, users can create direct, highly available, richer, and more dynamic web user interfaces that are close to native desktop applications.

Asynchronous javascript and xml (ajax) are not new technologies,Instead, it uses several existing technologies-including cascading style sheets (css), javascript, xhtml, xml, and extensible style language conversion (xslt)-to develop web applications that look and operate like desktop software.

[ajax execution principle]An ajax interaction starts with a javascript object called xmlhttprequest.As the name implies,It allows a client-side script to perform http requests and will parse a server response in XML format.The first step in the ajax process is to create an instance of xmlhttprequest. Use the http method (get or post) to process the request,And set the target url to the xmlhttprequest object.

When you send an http request, you don't want the browser to hang and wait for a response from the server,replaced by,You want to continue to respond to user interface interactions through the page,And process them after the server response actually arrives.To complete it,You can register a callback function with xmlhttprequest,And dispatch the xmlhttprequest request asynchronously. Control is immediately returned to the browser,When the server response arrives,The callback function will be called.

[ajax practical application]

1. Initialize ajax

Ajax is actually calling the xmlhttprequest object, so first of all, we must call this object,We build a function that initializes ajax:

* Initialize an xmlhttp object
* /
function initajax ()
Var var ajax=false;
Try {
Ajax=new activexobject ("msxml2.xmlhttp");
} Catch (e) {
Try {
Ajax=new activexobject ("microsoft.xmlhttp");
} Catch (e) {
If (! Ajax &&typeof xmlhttprequest!="Undefined") {
Ajax=new xmlhttprequest ();
Return ajax;

You might say,This code is because only the IE browser can use the xmlhttp component.Not tested by me,firefox can also be used. Then before we perform any ajax operation,Must first call our initajax () function to instantiate an ajax object.

2. Use the get method

Now our first step is to execute a get request, adding that we need to get the data of /show.php&id=63, so what should we do?

//Change the link to:
<a href="#" onclick="getnews(1)"> News 1</a>
//and set a layer to receive news,And set to not show:
Construct the corresponding javascript function at the same time:
function getnews (newsid)
//If the parameter newsid is not passed in
If (typeof (newsid) == "undefined")
Return false;
//URL of ajax
Var var url="/show.php?id="+ newsid;
//Get the position of the news display layer
Var var show=document.getelementbyid ("show_news");
//Instantiate the ajax object
Var ajax=initajax ();
//Use get to make a request
Ajax.open ("get", url, true);
//Get execution status
Ajax.onreadystatechange=function () {
//If the execution is normal,Then assign the returned content to the layer specified above
If (ajax.readystate == 4&&ajax.status == 200) {
//send empty
Ajax.send (null);

Then when the user clicks on the "News 1" link,The corresponding layer below will show the acquired content,And the page is not refreshed.Of course, we omitted the show.php file above,We just assume that the show.php file exists,And it can work normally to extract the news with id 1 from the database. This method adapts to any element in the page,Including forms, etc.Actually in application,There are many operations on the form.For forms,The more used is the post method, which will be described below.

3. Use the post method

In fact, the post method is similar to the get method.It's just slightly different when executing ajax,Let's talk briefly.

Suppose there is a form for a user to enter information,We save user information to the database without refreshing,At the same time, give the user a hint of success.

//Build a form,Attributes such as action and method are not required in the form.
It's all up to ajax.
<Form name="user_info">
Name:<input type="text" name="user_name" /><br />
Age:<input type="text" name="user_age" /><br />
Gender:<input type="text" name="user_sex" /><br />
<Input type="button" value="submit form" onclick="saveuserinfo ()" >
//Build a layer that accepts the returned information:
We see that there is no need to submit targets and other information in the form above.
And the type of submit button is just button, so all operations are performed by the saveuserinfo () function in the onclick event.
Let's describe this function:
function saveuserinfo ()
//Get the return information layer
Var var msg=document.getelementbyid ("msg");
//Get form object and user information values
Var var f=document.user_info;
Var var username=f.user_name.value;
Var var userage=f.user_age.value;
Var usersex=f.user_sex.value;
//Receive form URL
Var var url="/save_info.php";
//Need post value, join each variable through&
Var poststr="user_name =" + username + "&user_age =" + userage + "&user_sex =" + usersex;
//Instantiate ajax
Var ajax=initajax ();

//Open the connection by post
Ajax.open ("post", url, true);
//Define the transmitted file http header information
Ajax.setrequestheader ("content-type", "application/x-www-form-urlencoded");
//Send post data
Ajax.send (poststr);
//Get execution status
Ajax.onreadystatechange=function () {
//If the execution status is successful,Then write the returned information to the specified layer
If (ajax.readystate == 4&&ajax.status == 200) {

The general process of using the post method is like this,Of course, the actual development situation may be more complicated,This requires developers to ponder slowly.

4. Asynchronous callback (pseudo ajax way)

In general,Using the ajax method of get and post, we can solve the current problem.Just the complexity of the application,Of course, in development, we may encounter when ajax cannot be used, but we need to simulate the effect of ajax, so we can use pseudo ajax to achieve our needs.

The general principle of pseudo ajax is that we are still ordinary form submission,Or somethingBut we are aiming at the submitted value as a floating frame,So the page doesn't refresh,But, we need to see the results of our execution,Of course, you can use javascript to simulate the prompt message.But this is not true,So we need our execution results to call back asynchronously,Tell us what the execution result looks like.

Suppose our need is to upload an image,And, you need to know the status after the picture is uploaded,For example, whether the upload is successful, the file format is correct, the file size is correct, and so on.Then we need our target window to return the execution result to our window,This can smoothly simulate the process of an ajax call. The following code is a bit more, And involves smarty template technology,If you do n’t know much,Please read the relevant technical information.

Upload file:upload.html

//Upload the form,Specify target attribute as floating frame iframe1
<Form action="/upload.php" method="post" enctype="multipart/form-data" name="upload_img" target="iframe1" >
Select the image to upload:<input type="file" name="image" ><br />
<Input type="submit" value="upload image" >
//Layer displaying prompt information
//Floating frame used as the target window
< iframe name="iframe1" width="0" height="0" scrolling="no" ></iframe>
Process uploaded php file:upload.php
/* Define constants * /
//Define the mime format allowed to upload
define ("upload_image_mime", "image/pjpeg, image/jpg, image/jpeg, image/gif, image/x-png, image/png");
//Image allowed size,byte
define ("upload_image_size", 102400);
//Image size is expressed in kb
define ("upload_image_size_kb", 100);
//Image upload path
define ("upload_image_path", "./upload/");
//Get allowed image format
$mime=explode (",", user_face_mime);
//Iterate through all allowed formats
foreach ($mime as $type)
If ($_files ["image"] ["type"] == $type)
//If the format is correct,And upload it without exceeding the size
if ($is_vaild && $_files ["image"] ["size"]<= user_face_size && $_files ["image"] ["size"] > 0)
If (move_uploaded_file ($_ files ["image"] ["tmp_name"], user_image_path. $_Files ["image"] ["name"]))
$Upload_msg="Upload image successfully!";
$Upload_msg="Failed to upload image file";
$Upload_msg="Upload image failed.
Maybe the file exceeds ". User_face_size_kb." Kb, or the image file is empty, or the file format is incorrect ";
//Parse the template file
$smarty->assign ("upload_msg", $upload_msg);
$smarty->display ("upload.tpl");

Template file:upload.tpl

{if $upload_msg!=""}
callbackmessage ("{$upload_msg}");
//Callback javascript function, used to display information in the parent window
function callbackmessage (msg)
//Open the layer where the parent window displays messages
Parent.document.getelementbyid ("message"). Style.display="block";
//write the message obtained in this window
Parent.document.getelementbyid ("message"). Innerhtml=msg;
//And set the message display to close the parent window automatically after 3 seconds
Settimeout ("parent.document.getelementbyid (" message "). Style.display =" none "", 3000);

The process of using asynchronous callback is a bit complicated,But basically realized the function of ajax and information prompt,If there are more information prompts to accept the template,Then you can also handle it by setting up layers.Let's adapt.

[Conclusion]This is a very good web development technology,Although appearing for a long time,But it's only slowly burning up until now,I also hope to bring a change to the web development community,Let's move towards the development of ria (rich client),Of course, there are advantages and disadvantages to anything,If you use javascript too much, the client will be very bloated,Bad for the user ’s browsing experience,How to achieve fast pro,Can also achieve a good user experience,This requires the joint efforts of web developers.

  • Previous C # open source AOP framework-KingAOP foundation
  • Next Detailed routing of Express