Learning AJAX

转载 2007年09月20日 15:02:00

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.
举报

相关文章推荐

learning jQuery 学习笔记十五(+jQuery 1.4.1 API)-- AJAX----load(url, [data], [callback])

注:本笔记内容摘自《jQuery基础教程》+ jQuery 1.4.1中文参考        AJAX表示一组首字母缩写词—Asynchronous JavaScript and XML(异步J...

learning jQuery 学习笔记十四(+jQuery 1.4.1 API)-- AJAX ----$.ajax([options])

注:本笔记内容摘自《jQuery基础教程》+ jQuery 1.4.1中文 jQuery.ajax([options])               &#...

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

树莓派 Learning 002 装机后必要的操作 --- 09 root用户 密码

树莓派 装机后必要的操作 — root用户 密码我的树莓派型号:Raspberry Pi 2 Model B V1.1 装机系统:NOOBS v1.9.2树莓派使用的Linux是debian系统,...

决胜Spark大数据时代企业级最佳实践:Spark Core&Spark SQL&GraphX&Machine Learning&Best Practice

王家林:Spark、Docker、Android技术中国区布道师。 联系邮箱18610086859@126.com  电话:18610086859  QQ:1740415547  微信号:18...

#Paper Reading# Curriculum Learning

论文大体内容: 本文考虑到人的学习,学的是经过组织的知识,才能学习得更快。那么对应到机器学习,是否能够通过改变学习的顺序(对知识进行简单的组织),提升机器学习的效果呢?本文经过实验,发现这确实是一个可...

论文笔记 Ensemble of Deep Convolutional Neural Networks for Learning to Detect Retinal Vessels in Fundus

最近读了几篇关于DRIVE数据集的文章,来完成斯坦福公开课cs231n最后的Final Project,还有zju两门课的作业,哈哈哈,一举三得(^__^) ~~ 大概目标就是分割血管,如下图...

AR/VR learning (3)--物体的运动与动画(iTween插件的使用)

这里写链接内容##1.iTween是一个轻量级的插件,是用来做物体的运动(其中有人说是动画,个人觉得运动比较合适),可以用来做物体的移动,变换,跳跃等iTween的安装如下。在unity3d中的ass...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)