AJAX学习及应用指南

原创 2006年06月09日 16:03:00

AJAX In Action

Code Down: http://www.manning.com/crane.

 

Ajax (Asynchronous JavaScript + XML)

 

For example DOM

window.onload=function(){

var hello=document.getElementById('hello');

hello.className='declared';

var empty=document.getElementById('empty');

addNode(empty,"reader of");

addNode(empty,"Ajax in Action!");

var children=empty.childNodes;

for (var i=0;i<children.length;i++){

children[i].className='programmed';

}

empty.style.border='solid green 2px';

empty.style.width="200px";

}

function addNode(el,text){

var childEl=document.createElement("div");

el.appendChild(childEl);

var txtNode=document.createTextNode(text);

childEl.appendChild(txtNode);

}

For example

document.getElementsByTagName("UL")

 

For example

function addListItemUsingInnerHTML(el,text){

el.innerHTML+="<div class='programmed'>"+text+"</div>";

}

 

Create XmlhttpRequest

function getXMLHTTPRequest() {

var xRequest=null;

if (window.XMLHttpRequest) {

xRequest=new XMLHttpRequest();

}else if (typeof ActiveXObject != "undefined"){

xRequest=new ActiveXObject

("Microsoft.XMLHTTP");

}

return xRequest;

}

 

 

 

var READY_STATE_UNINITIALIZED=0;

var READY_STATE_LOADING=1;

var READY_STATE_LOADED=2;

var READY_STATE_INTERACTIVE=3;

var READY_STATE_COMPLETE=4;

var req;

function sendRequest(url,params,HttpMethod){

if (!HttpMethod){

HttpMethod="GET";

}

req=getXMLHTTPRequest();

if (req){

req.onreadystatechange=onReadyStateChange;

req.open(HttpMethod,url,true);

req.setRequestHeader

("Content-Type", "application/x-www-form-urlencoded");

req.send(params);

}

}

function onReadyStateChange(){

var ready=req.readyState;

var data=null;

if (ready==READY_STATE_COMPLETE){

data=req.responseText;

}else{

data="loading...["+ready+"]";

}

//... do something with the data...

}

 

 

 

For Example

<html>

<head>

<script type='text/javascript'>

var req=null;

var console=null;

var READY_STATE_UNINITIALIZED=0;

var READY_STATE_LOADING=1;

var READY_STATE_LOADED=2;

var READY_STATE_INTERACTIVE=3;

var READY_STATE_COMPLETE=4;

function sendRequest(url,params,HttpMethod){

if (!HttpMethod){

HttpMethod="GET";

}

req=initXMLHTTPRequest();

if (req){

req.onreadystatechange=onReadyState;

req.open(HttpMethod,url,true);

req.setRequestHeader

("Content-Type", "application/x-www-form-urlencoded");

req.send(params);

}

}

function initXMLHTTPRequest(){

var xRequest=null;

if (window.XMLHttpRequest){

xRequest=new XMLHttpRequest();

} else if (window.ActiveXObject){

xRequest=new ActiveXObject

("Microsoft.XMLHTTP");

}

return xRequest;

}

function onReadyState(){

var ready=req.readyState;

var data=null;

if (ready==READY_STATE_COMPLETE){

data=req.responseText;

}else{

data="loading...["+ready+"]";

}

toConsole(data);

}

function toConsole(data){

if (console!=null){

var newline=document.createElement("div");

console.appendChild(newline);

var txt=document.createTextNode(data);

newline.appendChild(txt);

}

}

window.onload=function(){

console=document.getElementById('console');

sendRequest("data.txt");

}

</script>

</head>

<body>

<div id='console'></div>

</body>

</html>

 

 

 

Early Ajax solutions using IFrames are described at http://developer.apple.com/internet/webcontent/iframe.html.

 

The AJAX Flow

 Figure 1

The following items represent the setups of an AJAX interaction as they appear in Figure 1.

1.                   A client event occurs.

2.                   An XMLHttpRequest object is created and configured.

3.                   The XMLHttpRequest object makes a call.

4.                   The request is processed by the ValidateServlet.

5.                   The ValidateServlet returns an XML document containing the result.

6.                   The XMLHttpRequest object calls the callback() function and processes the result.

7.                   The HTML DOM is updated.

Example

<script type="text/javascript">

 

function AJAXInteraction(url, callback) {

 

    var req = init();

    req.onreadystatechange = processRequest;

       

    function init() {

      if (window.XMLHttpRequest) {

        return new XMLHttpRequest();

      } else if (window.ActiveXObject) {

        return new ActiveXObject("Microsoft.XMLHTTP");

      }

    }

   

    function processRequest () {

      // readyState of 4 signifies request is complete

      if (req.readyState == 4) {

        // status of 200 signifies sucessful HTTP call

        if (req.status == 200) {

          if (callback) callback(req.responseXML);

        }

      }

    }

 

    this.doGet = function() {

      req.open("GET", url, true);

      req.send(null);

    }

}

 

function validateUserId() {

    var target = document.getElementById("userid");

    var url = "validate?id=" + encodeURIComponent(target.value);   

    var target = document.getElementById("userid");

    var ajax = new AJAXInteraction(url, validateCallback);

    ajax.doGet();

}

 

function validateCallback(responseXML) {

   var msg = responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;

   if (msg == "false"){

       var mdiv = document.getElementById("userIdMessage");

       // set the style on the div to invalid

       mdiv.className = "bp_invalid";

       mdiv.innerHTML = "Invalid User Id";

       var submitBtn = document.getElementById("submit_btn");

       submitBtn.disabled = true;

    } else {

       var mdiv = document.getElementById("userIdMessage");

       // set the style on the div to valid

       mdiv.className = "bp_valid";

       mdiv.innerHTML = "Valid User Id";

       var submitBtn = document.getElementById("submit_btn");

       submitBtn.disabled = false;

    } 

}

</script>

 

How to call

<input type="text" size="20" id="userid" name="id" autocomplete="off" onkeyup="validateUserId()">

 

AJAX Use Scene

Autocomplete

Autocomplete provides a simplified means of data navigation as the user enters a request in an HTML form. When faced with a large set of data, the user can be presented with a list of potential completions as the data is entered. Selecting one of the completions ensures that the user is entering data that exists on the server.

Consider a name finder web application inside a large corporation. Details about an individual can be obtained just from entering the first few characters of the first or last name, as in Figure 2. The user can then navigate to the user in question with one click.

Figure 2: Autocompletion of a Name

Progress Bar

In web applications, a server-side task may take some time to complete. This time may extend longer than the time out of an HTTP interaction. Frustrated users may resubmit a form or quit a session when they do not know how long the task will take. Typically, web applications use page refreshes to track the progress of a server-side operation, which can be distracting and not accurate. AJAX can be used to track the progress of a server-side operation in an HTML page without refreshing the HTML page. The user will see the progress of the server-side operation graphically in Figure 3.

Figure 3: Progress Bar

Refreshing Data

Providing up-to-date data or server notifications to an HTML page is important in the web world, where data is constantly changing. Although this is not push technology in a literal sense, it is simulated by polling from the client using AJAX interactions. When data needs to be updated or notifications need to be made, the HTML page is dynamically changed. Figure 4 shows a server-side counter being displayed in an HTML page. The counter will update in the background of the page.

Figure 4: Server-side Counter Shows Refreshing Data

Real-Time Validation

Not all form fields can be validated on the client using JavaScript technology alone. Some types of form data require server-side validation logic. Conventional web applications have used page refreshes to do this type of validation, but it can be a little distracting.

Consider a web application that requires a unique user ID. Using AJAX interactions, the user can know while typing whether or not the ID is valid (Figure 5).

Figure 5: Invalidating the ID as User Types

When a user enters an invalid user ID, the application disables the submit button and presents a message to the user (Figure 6).

Figure 6: Validating the ID as User Types

The user knows right away that the user ID is available and valid.

机器学习实践指南:案例应用解析(第二版)

数学之路系列主要博文已经整理出书,请多指导~       《机器学习实践指南:案例应用解析》是机器学习及数据分析领域不可多得的一本著作,也是为数不多的既有大量实践应用案例又包含算法理论剖析的著作...
  • u010255642
  • u010255642
  • 2014年04月17日 19:40
  • 8327

Ajax 很全很完整教程

Ajax 完整教程 第 1 页 Ajax 简介 Ajax 由 HTML、JavaScript™ 技术、DHTML 和 DOM 组成,这一杰出的方法可以将笨拙的 Web 界面转化成交互性的 ...
  • github_36111469
  • github_36111469
  • 2016年11月23日 23:29
  • 1413

Linux的学习路线图

一、学习Linux的基本要求 1. 掌握至少50个以上的常用命令。 2. 熟悉Gnome/KDE等X-windows桌面环境操作 。 3. 掌握.tgz、.rpm等软件包的常用安装方法 4. 学...
  • elsery
  • elsery
  • 2016年04月07日 13:26
  • 605

《Web应用安全权威指南》学习笔记

第1章     什么是Web应用的安全隐患 第2章     搭建试验环境 邮件发送服务器Postfix POP3服务器Dovecot SSH服务器OpenSSH Web应用调试工具Fiddl...
  • jiangtaozy
  • jiangtaozy
  • 2017年01月06日 13:02
  • 905

《web应用安全权威指南》心得

《web应用安全权威指南》读书心得 LandGrey 漏洞修补与防范 渗透测试
  • c465869935
  • c465869935
  • 2017年01月12日 15:53
  • 659

Ajax深入学习笔记

最近在学习ajax,下面整理了一下学习的内容,以便巩固用。 先来看看为什么要用ajax,也就是同步和异步是什么:同步和异步同步的意思就是客户端提交表单,发起请求后需要一直等待服务器端的响应,收到服务...
  • VivianHope
  • VivianHope
  • 2015年06月03日 15:54
  • 1674

Ajax学习总结(一)

Ajax学习(一) 一、      什么是ajax 1、Ajax(Asynchronous JavaScript and XML)使用脚本操纵HTTP的Web应用架构。 2、所有的浏览器都支持X...
  • u010913443
  • u010913443
  • 2016年08月13日 17:31
  • 1015

AJAX学习-到底是个什么东西

AJAX 是将咱们之前学到的HTML、CSS、XML、Js等web知识结合起来使用的一门技术,通过XMLHttpRequest对象实现异步的操作,可以在不重新加载整个页面的情况下,与服务器交换数据并更...
  • u010168160
  • u010168160
  • 2015年01月05日 07:55
  • 5173

Ajax应用场景-Ajax适合的应用场合

Ajax不是万能的,在适合的场合使用Ajax,才能充分发挥它的长处,改善系统性能和用户体验,绝不可以为了技术而滥用。Ajax的特点在于异步交互,动态更新web页面,因此它的适用范围是交互较多,频繁读取...
  • qq_21439971
  • qq_21439971
  • 2015年10月18日 20:19
  • 5171

Kubernetes权威指南学习笔记(一)

概念 Kubernetes是谷歌严格保密十几年的秘密武器——Borg的一个开源版本,是Docker分布式系统解决方案。 名词 Borg Borg是谷歌内部使用的大规模集群管理系统,...
  • keysilence1
  • keysilence1
  • 2017年04月20日 10:17
  • 2563
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:AJAX学习及应用指南
举报原因:
原因补充:

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