Chinaunix首页 | 论坛 | 博客
  • 博客访问: 17411
  • 博文数量: 22
  • 博客积分: 920
  • 博客等级: 准尉
  • 技术积分: 220
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-27 15:19
文章分类

全部博文(22)

文章存档

2010年(22)

我的朋友
最近访客

分类: 系统运维

2010-03-27 16:38:51

 AJAX TUTORIAL
1. WHAT IS AJAX?
    AJAX is short  for  Asynchronous JavaScript and XML.
 AJAX is based on JavaScript and HTTP requests.
 AJAX is not a new programming language, but a new way to use existing standards.
 AJAX is the art of trading data with a web server, and changing parts of a web page, without reloading the whole page.
 AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications.
 With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.
 AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
 The AJAX technique makes Internet applications smaller, faster and more user-friendly.
2. AJAX uses the XMLHttpRequest object
 To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
 With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.
 With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
3. The XMLHttpRequest object
 By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!
 AJAX was made popular in 2005 by Google (with Google Suggest).
 Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
 The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).
4. A Sample
 
 
 
 
 
  


  

Click to let AJAX change this text


  

  
  
 
 
5. Two important methods of XMLHttpRequest
 To send a request to a web server, we use the open() and send() methods.
5.1. open()
 The open() method takes three arguments. The first argument defines which method to use (GET or POST). The second argument specifies the name of the server resource (URL). The third argument specifies if the request should be handled asynchronously.
5.2. send()
 The send() method sends the request off to the server. If we assume that requested a file called "time.asp", the code would be:
 url="time.asp"; //absolute path or relative path
 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
 In the example we assume that the current web page and the requested resource are both in the same file directory.
6. Two important properties of XMLHttpRequest
 The XMLHttpRequest object has 3 important properties:
 The responseText property
 The readyState property
 The onreadystatechange property
6.1. responseText
 The XMLHttpRequest object stores any data retrieved from a server as a result of a server request in its responseText property.
 In the previous chapter we copied the content of the responsText property into our HTML with the following statement:
 document.getElementById('test').innerHTML=xmlhttp.responseText
 
6.1.1 XMLHttpRequest Open - Using False
 In the examples (from the previous pages) we used this simplified syntax:
 xmlhttp.open("GET",url,false);//'false' tells tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed.
 xmlhttp.send(null);
 document.getElementById('test').innerHTML=xmlhttp.responseText;
 For small applications and simple server request, this might be OK. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.
 
6.1.2 XMLHttpRequest Open - Using True
 By changing the third parameter in the open call to "true", you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent.
 Because you cannot simply start using the response from the server request before you are sure the request has been completed, you need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion.
 In this onreadystatechange function you must test the readyState property before you can use the result of the server call.
 Simply change the code to:
 xmlhttp.onreadystatechange=function(){
  if(xmlhttp.readyState==4)
  {
   document.getElementById('test').innerHTML=xmlhttp.responseText
  }
 }
 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
 
6.2. readyState
 The readyState property
 The readyState property holds the status of the server's response.
 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
  
6.3. onreadystatechange
 The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readyState property changes.
 You can store a full function in the property like this:
 xmlhttp.onreadystatechange=function()
 {
  if(xmlhttp.readyState==4)
   {document.getElementById('test').innerHTML=xmlhttp.responseText}
 }
 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
 Or you can store the name of a function like this:
 xmlhttp.onreadystatechange=state_Change;
 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
 ...
 function state_Change()
 {
  if(xmlhttp.readyState==4)
   {document.getElementById('test').innerHTML=xmlhttp.responseText}
 }
7. XMLHttpRequest Object can Request any Data
 With the XMLHttpRequest object, you can request any web resource from a server.
 You can request TXT files, HTML files, XML files, pictures or any data that is accessible from the Internet.
 AJAX is about creating clever applications that can use the data.
 --------------------------------------------------------------------------------
 Requesting Text Files
  Many AJAX applications requests pure text files to retrieve data for the application.
 --------------------------------------------------------------------------------
 Requesting XML Files
  A very common AJAX method is to request XML files to retrieve application data.
 --------------------------------------------------------------------------------
 Requesting ASP or PHP Files
  Requesting an ASP or PHP file is the most common way to access database information.
 --------------------------------------------------------------------------------
 Requesting HTML Files
  Requesting HTML files is a common method for filling out different information on a web page
 --------------------------------------------------------------------------------
 Submitting Forms
  With AJAX you can easily submit form data without having to reload the page.
8. AJAX Suggest example
 The following AJAX example will demonstrate how a web page can communicate with a web server while a user enters data into an HTML form.
 --------------------------------------------------------------------------------
 The AJAX HTML page
 This is the HTML page. It contains a simple HTML form and a link to a JavaScript.
 
 
 
 
 
 
First Name:

 

Suggestions:


 
 
 --------------------------------------------------------------------------------
 The AJAX JavaScript
 This is the JavaScript code, stored in the file "clienthint.js":

 var xmlhttp
 function showHint(str)
 {
  if (str.length==0)
  {
   document.getElementById("txtHint").innerHTML="";
   return;
  }
  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
   alert ("Your browser does not support XMLHTTP!");
   return;
  }
  var url="gethint.asp";
  url=url+"?q="+str;
  url=url+"&sid="+Math.random();
  xmlhttp.onreadystatechange=stateChanged;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
 }

 function stateChanged()
 {
  if (xmlhttp.readyState==4)
  {
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
  }
 }
 //The purpose of the GetXmlHttpObject() function is to solve the problem of creating different XMLHTTP objects for different browsers:
 function GetXmlHttpObject()
 {
  if (window.XMLHttpRequest){  // code for IE7+, Firefox, Chrome, Opera, Safari
   return new XMLHttpRequest();
  }
  if (window.ActiveXObject){  // code for IE6, IE5
   return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
 }
 --------------------------------------------------------------------------------
 
 The AJAX server page - ASP and PHP
There is no such thing as an AJAX server. AJAX pages can be served by any internet server.

The server page called by the JavaScript in the example from the previous chapter is a simple ASP file called "gethint.asp".

Below we have listed two examples of the server page code, one written in ASP and one in PHP.


--------------------------------------------------------------------------------
注意:服务器端在Response.Write("...")后,客户端调用XMLHttpRequest.responsetext拿到的是所有内容
即write的内容以及页面所有内容。
但是在innerhtml赋值时一般会解析,我觉得应该是解析第一个可以赋值的元素。
比如"aa",拿到的是aa
"ss",拿到的是ss
但是若后有一些特殊字符串东西时,可能会出错。
故最好自行处理。
我们也可以在服务器端把一些结构化的数据生成xml,写进去,传到客户端。


还有一种技术是,服务器端传一个Javascript脚本到客户端,由客户端去调用那个Javascript脚本,比如ASP.Net的ScriptManager。
以上是AJAX的基本原理,核心即为XMLHttpRequest。
一些通用的AJAX框架应该是在此基础上进行一些封装,便于使用。

另外利用AJAX还可以实现服务器端推送技术(长连接),一般我们是客户端发送一个Request后,服务器端响应,然后断开HTTP连接(实际上是基于TCP实现的)。XMLHttpRequest.open()的第三个方法若为true,则会异步等待服务器端响应(这个时候应该是一直保持连接,否则服务器端不知道该把数据返回给哪个客户端)。我们在服务器端的处理,通常是立即返回结果。若要保持长连接,那么我们只是在有数据到达的时候返回结果。客户端刷新后,又再发一个异步请求。这样就相当于是实现了实时的服务器端推送,因为只有服务器端发送结果后才会断开连接,并且又马上重连。而不用客户端定时调用AJAX发送请求获取延时数据。
以上是基于AJAX的服务器端推送技术(COMET,常见的一种实现为Pushlet)
还有一种是利用IFrame的src属性来传递数据,具体可网上查阅相关资料。
注意:长连接虽然能够实现实时传递数据,但是性能瓶颈,客户端数量较多的时候,服务器端的连接较多,造成服务器端性能下降,另外HTTP1.1规定,对于同一个Domain,最多同时保持两个连接,所以长连接数量多,会影响后面打开页面的响应,甚至堵塞。


阅读(283) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~