mushme 发表于 2013-1-23 01:44:09

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

总有人把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

[*]test.html
[*]test2.html
[*]百度ajax不能跨域,所以这里得不到百度的页面
<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;}}
页: [1]
查看完整版本: 最简单的ajax,ajax读取页面内容