现在的位置: 首页 > 综合 > 正文

Learning AJAX

2013年01月12日 ⁄ 综合 ⁄ 共 8288字 ⁄ 字号 评论关闭

This is a two-part article. In these two parts I'll try to describe what AJAX is, and how to use AJAX in PHP and JSP. Later we will use some advanced JSP tag libraries to make cool AJAX-based web applications.

Please remember, AJAX is not a new programming language, so you don't have to learn anything new. AJAX involves just using the existing standards (JavaScript and XML) in a different way. AJAX became popular because of Google in 2005. AJAX becomes a common ingredient in web 2.0-based web applications.
Why do we need AJAX? Often web-based applications are not as user-friendly as desktop applications. Using AJAX, we can create a feature-rich and easy-to-use graphical user interface for web applications. AJAX is supported by most of the web browsers available today.
Using AJAX technology we can get information from a server in the background without reloading the web page. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, using an XMLHttpRequest object. This object makes XML requests over HTTP protocol. After getting the response from the server, new information can be placed in the current web page without reloading it. This XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7.
First we need to create an XMLHttpRequest object. Then using this object, we will request a web page from the server. JavaScript will then monitor the change of state of the request. If the request is complete and the response is successful, then the content from the web page requested will be returned as the response. This response can be in either of two formats, String or XML. Then we can use the response in your web pages. Next we will go into these steps in detail. 

 

JavaScript has a built-in XMLHttpRequest object for requesting web pages. You can use that for Firefox, Safari, and Opera. For Internet Explorer use ActiveXObject. But it is different for IE 5.0 and IE 6.0+. The following code creates an XMLHttpRequest.
var req;
try
{
  // Firefox, Opera, Safari
  req = new XMLHttpRequest();
}
catch (e)
{
  // Internet Explorer
  try
  {
    //For IE 6
    req = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {
    try
    {
      //For IE 5
      req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
      alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera'); 
    }
  }
}
Here we are first trying to get create a XMLHttpRequest using the built-in function. If it fails we will try using ActiveXObject("Msxml2.XMLHTTP"), and if that fails as well we will try ActiveXObject("Microsoft.XMLHTTP"). If all of these fail, we will alert the user that his browser does not support AJAX. Use ActiveXObject("Msxml2.XMLHTTP") for Internet Explorer 6 and above. Use ActiveXObject("Microsoft.XMLHTTP") for Internet Explorer 5.
Now we have the XMLHttpRequest as a variable req. We now can request a server side page using the GET or POST method.
req.open("GET","somedata.php");
req.send(null);
Here we try to get somedate.php using the HTTP GET method.
We now wait for the state change of this request.
req.onreadystatechange = handleResponse;
function handleResponse(){
  if(req.readyState == 4 && req.status == 200){
    //returned text from the PHP script
    var response = req.responseText;
  }
}
The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State
Description
0
The request is not initialized
1
The request has been set up
2
The request has been sent
3
The request is in process
4
The request is complete
If the readyState value is 4, it indicates the request is complete, and a status value of 200 means a successful response. Some possible values for request status are 4xx or 5xx. These values of the request status means the request failed due to a wrong URL or authentication problem or for some other reason. As mentioned earlier the response can be either in String or XML format. To get a string value use responseText. To get an XML value for the response, you need to use responseXML.
Now you can use this response in your current web page. We now have AJAX ready to use. You can add these JavaScript codes to one file and name it ajax.js. This is a better practice. Here is the complete ajax.js.
function createRequestObject(){
  var req;
  try
  {
    // Firefox, Opera, Safari
    req = new XMLHttpRequest();
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
      //For IE 6
      req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        //For IE 5
        req = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
      }
    }
  }
  return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
  if(method == 'get' || method == 'GET'){
    http.open(method,url,true);
    http.onreadystatechange = handleResponse;
    http.send(null);
  }
}
function handleResponse(){
  if(http.readyState == 4 && http.status == 200){
    var response = http.responseText;
    if(response){
      document.getElementById("ajax_res").innerHTML = response;
    }
  }
}
Here you can see that I put the response as the innerHTML of a DIV with an id equal to "ajax_res". I also created a function called sendRequest which takes two strings as parameters. The first parameter is the HTTP method, either GET or POST. The second parameter is the URL that will be invoked using the XMLHttpRequest object in background. This function will be called from PHP or JSP pages in the next example codes.
Now add this JavaScript file in your web page like this -
<script type="text/javascript" language="Javascript" src="ajax.js"></script>
Then add a JavaScript code to call the sendRequest function of ajax.js. You need a DIV tag to display the response.
<div id="ajax_res"></div>
Now you have everything ready for using AJAX in your PHP web pages. We will now try a simple example to get the server time using AJAX. First we need to develop the server side PHP code that will return server date.
<?php
  echo date("m.d.y");
?>
Now save this PHP code as date.php. This PHP page will output server date. As discussed earlier I put all necessary JavaScript codes for AJAX in ajax.js. the next thing we need to develop is our main PHP page that will make the request for date.php.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <script type="text/javascript" language="Javascript"
src="ajax.js"></script>
    <meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
    <title>PHP using AJAX</title>
  </head>
  <body>
    <a onclick="sendRequest('GET','date.php')"href="#">Server
Date:</a>
    <div id="ajax_res">Server Date will replace this text.</div>
  </body>
</html>
Here first we add ajax.js using a script tag. Then I add a hyperlink with an onClick event to call the sendRequest function of ajax.js with 'GET' as the HTTP method and the URL to the server side PHP, date.php. After that I add a DIV tag with an id attribute equal to ajax_res.
If the user of this PHP page clicks this hyperlink, date.php will be requested in background, and the output of date.php will replace the text within the DIV tags. Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and getting the HTTP Response. There is also another way to request server side codes in PHP without using XMLHttpRequest, but to me that is not AJAX.
Now let me show you an example that is similar to the one above. In this example we will request a server side JSP to get the server date time, and then display the server time in the current JSP page.
The first thing we need to develop is the server side JSP code to get the server date time. The following JSP code will output the server date time.
<%=new java.util.Date()%>
Save this as index.jsp.
We already have all the necessary JavaScript codes in ajax.js.
Now we need to develop the invoker JSP; let's call this caller.jsp. Here is the JSP code for caller.jsp.
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <script src="ajax.js"></script>
    <meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
    <title>JSP Page using AJAX</title>
  </head>
  <body>
    <a onclick="sendRequest('GET','index.jsp')"href="#">Server
Date Time:</a>
    <div id="ajax_res">Server Date Time will replace this
text.</div>
  </body>
</html>
This caller.jsp has a <div> element with the id='ajax_res'. When the user clicks the link 'Server Date Time:' as shown below, the JavaScript function sendRequest from ajax.js will be called to get the data from 'index.jsp' using the HTTP GET method. The output of this index.jsp will replace the text within <div id="ajax_res">and </div>. The output of caller.jsp before clicking the link is:
The output of caller.jsp after invoking the index.jsp using AJAX is:
This way you can use AJAX with JSP for retrieving information from a database or from any file kept in the server, or you can send the user information to a server and get the response.
We discussed AJAX -- why we should use AJAX, what is required to use AJAX, and then we learned how to use AJAX in PHP pages as well as JSP pages. We will see some advanced usage of AJAX in the next part. Also in the next part of this article I will discuss some advanced and open source JSP tag libraries to create cool AJAX-based web applications.

抱歉!评论已关闭.