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.

Ajax learning

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。 打法...
  • wcq3692012
  • wcq3692012
  • 2014年06月28日 05:31
  • 212

机器学习分支:active learning、incremental learning、online machine learning

1. Active learningActive learning 是一种特殊形式的半监督机器学习方法,该方法允许交互式地询问用户(或者其他形式的信息源 information source)以获取对...
  • lanchunhui
  • lanchunhui
  • 2017年05月02日 21:44
  • 803

Deep learning系列(十三)Transfer learning 和 caffe Fine-tuning

介绍了Transfer Learning及在用caffe进行微调。
  • u012526120
  • u012526120
  • 2015年10月29日 20:41
  • 8675

Online learning 的一些简单认识

Online learning 的一些简单认识   Online learning是机器学习中的一种方法。 其目的是正确预测数据的类别,并且在每次预测后,该结果用来更新修正预测模型,用于对以后...
  • u013711360
  • u013711360
  • 2016年03月26日 20:20
  • 2320

Discriminative Learning和Generative Learning的总体区别

Discriminative 学习算法是一类模型化输入(X)输出(Y)的关系的方法。Discriminative Learning要求X的各个项是相互独立变化的。只需了解X对Y的决定关系,即model...
  • dllian
  • dllian
  • 2012年04月24日 09:52
  • 941

Andrew Ng 《Machine Learning》第一讲——Supervised Learning & Unsupervised Learning 学习笔记

一般的,机器学习的问题可分为有监督学习(Supervised)和无监督学习(Unsupervised)两类。有监督学习需要有一个包含“正确答案”的数据集,例如房价,是否恶性肿瘤,有监督学习算法解决的目...
  • zhonglj0314
  • zhonglj0314
  • 2017年02月07日 18:52
  • 605

Bengio大神的《Deep Learning》全书已完稿可获取全书电子版

【推荐】Bengio大神的《Deep Learning》全书已完稿可获取全书电子版 2016-04-07 机器学习研究会 点击上方“机器学习研究会”可以订阅哦!摘要  视觉机器人 经过两年半的努...
  • j_study
  • j_study
  • 2016年04月09日 12:04
  • 15892

Transductive Learning vs Inductive Learning

Transductive Learning:从彼个例到此个例,有点象英美法系,实际案例直接结合过往的判例进行判决。关注具体实践。Inductive Learning:从多个个例归纳出普遍性,再演绎到个...
  • wendox
  • wendox
  • 2016年01月07日 10:08
  • 1592

【深度学习入门—2015MLDS】1. What is Machine Learning, Deep Learning and Structured Learning?

2015MLDS第1课——机器学习、深度学习和结构化学习
  • lecholin
  • lecholin
  • 2017年08月19日 10:56
  • 647

《reinforcement learning:an introduction》第一章《The Reinforcement Learning Problem》总结

由于组里新同学进来,需要带着他入门RL,选择从silver的课程开始。 对于我自己,增加一个仔细阅读《reinforcement learning:an introduction》的要求。 因为之前读...
  • mmc2015
  • mmc2015
  • 2017年07月10日 17:27
  • 1094
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Learning AJAX
举报原因:
原因补充:

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