javascript学习笔记 (六)-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));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值