六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 32|回复: 0

最简单的ajax,ajax读取页面内容

[复制链接]

升级  4.67%

58

主题

58

主题

58

主题

举人

Rank: 3Rank: 3

积分
214
 楼主| 发表于 2013-1-29 11:35:48 | 显示全部楼层 |阅读模式
总有人把ajax搞得异常复杂,其实蛮简单的,给新手一个信心,以下是一个简单的例子,通过ajax来加载其它url的内容。
ajax.html,主页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8" /><script type="text/javascript" src="ajax.js"></script><style type="text/css">#previewWin{background-color:#FF9;widht:400px;height:100px;padding:5px;position:absolute;visibility:hidden;top:10px;left:10px;border:1px #CC0 solid;clip:auto;overflow:hidden;}</style></head><body>直接用浏览器打开是看不到ajax请求的,需要放到服务器目录下才可以哦。如有问题QQ:45886484
<div id="previewWin"></div></body></html>test.html,用来被主页面加载的内容


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>test.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html;charset=utf-8" />        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  </head>    <body>    这里是test.html的内容,可以被读取 <br>  </body></html>

ajax.js,加载内容的js
window.onload=initAll;var xhr=false;var xPos,yPos;function initAll(){var allLinks=document.getElementsByTagName("a");for(var i=0;i<allLinks.length;i++){allLinks.onmouseover=showPreview;allLinks.onmouseout=hidePreview;}}function showPreview(evt){getPreview(evt);return false;}function hidePreview(){document.getElementById("previewWin").style.visibility="hidden";}function getPreview(evt){if(evt){var url=evt.target;}else{evt=window.event;var url=evt.srcElement;}xPos=evt.clientX;yPos=evt.clientY;if(window.XMLHttpRequest){xhr=new XMLHttpRequest();}else{if(window.ActiveXObject){try{xhr=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}}if(xhr){xhr.onreadystatechange=showContents;xhr.open("GET",url,true);xhr.send(null);}else{alert("不能发送ajax请求");}}function showContents(){var preWin=document.getElementById("previewWin");if(xhr.readyState==4){if(xhr.status==200){preWin.innerHTML=xhr.responseText;}else{preWin.innerHTML="ajax请求出错";}preWin.style.top=parseInt(yPos)+2+"px";preWin.style.left=parseInt(xPos)+2+"px";preWin.style.visibility="visible";preWin.onmouseout=hidePreview;}}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表