• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
繁星
不要浪费时间
博客园    首页    新随笔    联系   管理    订阅  订阅

[翻译]javascript学习笔记 (六)-ajax相关

ajax相关
ajax大多数是通过服务器端语言来获取所需的数据,javascript发出请求,服务器将查询数据库然后返回数据。数据可以通过几种形式返回。如果他是结构化的,你可以用xml或json格式。如果他是非常简单的数据,例如文本,一般人们直接返回这种数据。

创建一个xmlhttp对象

if(typeof(XMLHttpRequest)!='undefined'){
    
var getXMLHttpObj = function(){ return new XMLHttpRequest(); }
} 
else {
    
var getXMLHttpObj = function(){
        
var activeXObjects = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0',
        'Msxml2.XMLHTTP.
3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
        
for(var i=0; i<activeXObjects.length; i++){
            
try{
                
return new ActiveXObject(activeXObjects[i]);
            }
catch(err){}
        }
    }
}

任何支持XMLHttpRequest对象的浏览器都可以用这个内建的对象。IE7现在支持这个对象,但IE6或较老的版本不能支持,他们只能通过Microsoft的XMLHttpRequest ActiveX对象。

现在用XMLHttp对象向服务器端发送一个请求
var oXml = getXMLHttpObj();

oXml.open('GET', 'getData.php', 
true);
oXml.onreadystatechange 
= processingFunction;
oXml.send();

function processingFunction(){
    
if(oXml.readyState!=4) return; // our request is not done
    // we process the results here.  More on that later!
}

创建XMLHttp后,用open函数指定连接的参数,一共有3个参数:请求类型,url,是否为异步传输
第一个参数通常是GET或POST。如果你是要获取数据,通常使用GET,若是提交数据,则用POST

如何以何种数据格式传输呢?
XML vs JSON vs Text
XML是一个被普遍接受的标准。JSON是一个新的标准,他的数据更容易被我们理解且体积要小。
XML
<xml>
 
<contacts>
  
<person firstname="Joe" lastname="Smith" phone="555-1212" />
  
<person firstname="Sam" lastname="Stevens" phone="123-4567" />
 
</contacts>
</xml>

JSON:
{contacts:[
    {"firstname":"Joe", "lastname":"Smith",   "phone":"555-1212"},
    {"firstname":"Sam", "lastname":"Stevens", "phone":"123-4567"}
]}

JSON看起来像javascript代码
XML中以下的标签要被替代
     & --> &amp;
     < --> &lt;
     > --> &gt;
     " --> &quot;
     ' --> '
服务器端传过来的代码必须带有值为text/xml的content-type ,如果你获取的文件是xml扩展名,系统会自动添加。如果不是则应该手动添加信息。
PHP
<?php header('Content-type: text/xml'); ?>
ASP
<% response.contentType = "text/xml" %>

JSON的规则
对象以{}封闭
数组以[]封闭
所有的字符串加双引号
使用双引号需要用\转义

function processingFunction(){
    
if(oXml.readyState!=4) return; // our request is not done

    
// we process the results here.  More on that later!
}

当XMLHttp请求完毕,XMLHttp提供两个方法来返回数据: responseXML和 responseText。

function processingFunction(){
    
if(oXml.readyState!=4) return;

    
var xmlDoc   = oXml.responseXML;
    
var contacts = xmlDoc.selectNodes('/xml/contacts/person');

    alert('There are '
+contacts.length+' contacts!');

    
for(var i=0; i<contacts.length; i++){
        alert('Contact #'
+(i+1)+':\n\n'+
                'First Name: '
+contacts[i].getAttribute('firstname')+'\n'+
                'Last Name:  '
+contacts[i].getAttribute('lastname') +'\n'+
                'Phone #:    '
+contacts[i].getAttribute('phone')    +'\n');
    }
}

使用JSON格式
function processingFunction(){
    
if(oXml.readyState!=4) return;

    
var json = eval('('+oXml.responseText+')');

    alert('There are '
+json.contacts.length+' contacts!');

    
for(var i=0; i<json.contacts.length; i++){
        alert('Contact #'
+(i+1)+':\n\n'+
            'First Name: '
+json.contacts[i].firstname+'\n'+
            'Last Name:  '
+json.contacts[i].lastname +'\n'+
            'Phone #:    '
+json.contacts[i].phone    +'\n');
    }
}

JSON字符串可以使用eval()函数来转换。如果你信任数据的来源,你可以直接这样转换,若数据是从其他地方来,你应该进行JSON分析,以确保安全。

下面是一个示例
<table cellspacing="1" cellpadding="3" bgcolor="#000000" style="font-family:tahoma;font-size:10px;">
 
<tbody id="contactListTable">
  
<tr style="background-color:#CCF;">
   
<th>First Name</th>
   
<th>Last Name</th>
   
<th>Phone #</th>
  
</tr>
 
</tbody>
</table>

function loadContactListPage(n){
    
var oXML = getXMLHttpObj();
    oXML.open('GET', '
/img/10_json_file'+n+'.txt', true);
    oXML.onreadystatechange 
= function(){ doneLoading(oXML); }
    oXML.send('');
}

function doneLoading(oXML){
    
if(oXML.readyState!=4) return;

    
var json  = eval('('+oXML.responseText+')');
    
var table = document.getElementById('contactListTable');

    
for(var i=table.childNodes.length-1; i>1; i--){
        table.removeChild(table.childNodes[i]);
    }

    
for(var i=0; i<json.contacts.length; i++){
        
var tr  = document.createElement('TR');
        
var td1 = document.createElement('TD');
        
var td2 = document.createElement('TD');
        
var td3 = document.createElement('TD');

        tr.style.backgroundColor 
= i%2?'#FFF':'#E6E6E6';

        table.appendChild(tr);

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        td1.appendChild(document.createTextNode(json.contacts[i].firstname));
        td2.appendChild(document.createTextNode(json.contacts[i].lastname));
        td3.appendChild(document.createTextNode(json.contacts[i].phone));
    }
}

posted @ 2009-03-01 12:58  ※繁星※  阅读(158)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3