看尚硅谷学习ajax,跟着视频写的,改了半天,各种错误:
</pre><div id="details"><pre name="code" class="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" xml:lang="en" lang="en"> <head> <Meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>People at Clearleft</title> <style type="text/css"> @import url("clearleft.css"); </style> <script type="text/javascript"> window.onload = function(){ var aNodes = document.getElementsByTagName("a"); <span style="color:#009900;">//错误:getElement...没有s</span> for (var i = 0; i<aNodes.length; i++){ aNodes[i].onclick = function (){ var request = new XMLHttpRequest(); request.open("GET",this.href);<span style="color:#009900;"><span style="color:#009900;"><strong>// 错误:方法与URL顺序放错;URL写错成this.url</strong></span></span> request.send(null); request.onreadystatechange=function(){ if(request.readyState==4){ if(request.status==200||request.status==304) document.getElementById("details").innerHTML=request.responseText;<span style="color:#009900;"><strong><span style="color:#009900;">//document.getElementById</span> <span style="color:#009900;">//("details").innerHTML这样 服务器返回值直接赋给<div id="details"></div> 在同一页面中显示出来。</span></strong></span> } } return false; } } } </script> </head> <body> <h1>People</h1> <ul> <li> <a href="files/andy.html">Andy</a> </li> <li> <a href="files/richard.html">Richard</a> </li> <li> <a href="files/jeremy.html">Jeremy</a> </li> </ul> <div id="details"></div> </body> </html>
通过jquery实现ajax,可以大大简化复杂度:
<script type="text/javascript" src ="../scripts/jquery-1.9.1.js"> </script> <strong><span style="color:#009900;">//首先要调用js文件(错误:把这个写在下面的<script/>里面)</span></strong> <script type="text/javascript" > $(function(){ $("a").on("click",function(){ var url = this.href; $("#details").load(url); return false; }); });
跟上面的是一样的。这样是GET 请求,刷新时由于URL没有变,写出来之后再点击服务器不会重新返回,因此可以加上时间,是请求与前面不相同。
$(function(){ $("a").on("click",function(){ var args = {"time":new Date()}; <strong><span style="font-size:14px;"><span style="color:#009900;">//加入时间</span></span></strong> var url = this.href; $("#details").load(url,args); return false; }); });