1.Ajax的四个技术基石
javascript+css+dom+xmlhttpRequest
使用dom(文档对象模型)定义用户界面的结构,是一组可以使用javascript操作的可编程对象展现出web页面的结构
使用xmlhttpRequest以异步方式与服务器通信.
web页面的dom表示是一个树状结构,由元素或节点组成,节点还可能包含很多子结点.js引擎通过全局变量
document公开当前web页面的根节点,这个变量是所有dom操作的起点.
var childEl=document.createElement('div');//创建新元素
var el=document.getElementById('empty');
el.appendChild(childEl); //添加子节点
var txtNode=document.createTextNode(text);//创建文本元素
childEl.appendChild(txtNode);
var childer=empty.childNodes;//找子结点
for(var i=0;i<childern.length;i++)
{
childern[i].className='programmed'; //定义子结点的css样式
}
.programmed{
color: blue;
font-family: helvetica;
font-weight: bold;
font-size: 10px;
}
el.innerHtml="<div class='programmed'>"+text+"</div>";
css www.csszengarden.com
css www.meyerweb.com/eric/css
js边学边做 www.w3schools.com/js/js_examples_3.asp 交互式学习教程
2.重构
net.js
/*
url-loading object and a request queue built on top of it
*/
/* namespacing object */
var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url,method,params,contentType);
}
net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
if (!method){
method="GET";
}
if (!contentType && method=="POST"){
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
net.ContentLoader.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}
net.ContentLoader.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
net.ContentLoader.prototype.defaultError=function(){
alert("error fetching data!"
+"/n/nreadyState:"+this.req.readyState
+"/nstatus: "+this.req.status
+"/nheaders: "+this.req.getAllResponseHeaders());
}