Ajxa示例 - 读取服务器文件数据

下面是一个读取服务器数据的ajax示例,将下面的代码存到一html文件中,同一目录新建一message.txt文件,内容不为空,以看出效果,看到以下对话框,则测试成功。

Ajxa示例 - 读取服务器文件数据_第1张图片

 

message.txt内容:

If you can read this, you have successfully requested a text file from the server.

 

html源文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>read the data (XHR)</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <mce:script language="JavaScript" type="text/javascript"><!-- /*<!--[CDATA[*/ function test_fn(file_uri) { var xhr=false; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { } } } var rt=xhr; if(rt){ rt.onreadystatechange=function(){ if(rt.readyState==4){ if(rt.status==200 ||rt.status==304){ alert(rt.responseText); } } } rt.open("POST",file_uri,"true"); rt.setRequestHeader("content-type","application/x-www-form-urlencoded"); rt.send(null); } } /*]]-->*/ // --></mce:script> </head> <body> <p> <a href="message.txt" mce_href="message.txt" onclick="test_fn(this.href); return false;"> Click here to see the contents of a text file </a> </p> </body> </html>

 

 

 

当然写成模块式的方式更好,

function getHttpObject() { var xhr=false; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); }else if(window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { } } } return xhr; } function dispResp(rt) { alert(rt.responseText); } function getTheData(file_uri) { var rt=getHttpObject(); if(rt){ rt.onreadystatechange=function(){ if(rt.readyState==4){ if(rt.status==200 ||rt.status==304){ dispResp(rt); } } } rt.open("POST",file_uri,"true"); rt.setRequestHeader("content-type","application/x-www-form-urlencoded"); rt.send(null); } }

你可能感兴趣的:(Ajxa示例 - 读取服务器文件数据)