Ajax & PHP 边学边练 之一 Ajax基础

       Ajax其实已经使用很久了,但一直也没有时间正经的找本书系统看看,最近时间比较充裕可以好好补习一下了。本系列是基于Ajax和PHP结合进行讲解,主要是想和正在学习或想要学习Ajax的朋友分享下经验。希望大家多多拍砖共同交流。

       众所周知,Ajax并不是一个新生的语言,它是一系列语言的结合体:HTML/XHTML、CSS、DOM、XML、XSLT、XMLHttp、JavaScript。可以说Ajax涉及的知识面的确是很广的,在Web开发中为我们提供了很方便的交互式用户体验模式。以往我们浏览网页的原理是由Client向Server提交页面申请,再由Server将申请通过HTTP传回给Client生成浏览页面:

httpreq

       使用Ajax后的工作原理如下图,可见通过Ajax在用户交互方面有了很大改进,用户可以不用为提交了Form而长时间等待服务器应答,而且通过Ajax也可以开发出华丽的Web交互页面。

ajax

       在使用Ajax时,需要创建XMLHttpRequest对象,不同浏览器的创建方式略有不同:

var xmlHttp=null;  try  {    // Firefox, Opera 8.0+, Safari 非IE浏览器    xmlHttp=new XMLHttpRequest();  }  catch (e)  {    //IE浏览器    try    {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }    catch (e)    {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");    }  }

 

       在利用Ajax向服务器提交请求时,需要先确定三点:

       1. 使用GET或POST方式提交请求?

       2. 需要请求的页面(Page)或代码(Script)?

       3. 将请求的页面或代码加载到页面什么位置?

function makerequest(serverPage, objID) {    //将要被替换的页面位置obj    var obj = document.getElementById(objID);    //发出页面(serverPage)请求    xmlhttp.open("GET", serverPage);    xmlhttp.onreadystatechange = function()    {      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {         //将服务器返回的信息替换到页面位置obj         obj.innerHTML = xmlhttp.responseText;      }    }    xmlhttp.send(null);  }

 

       其中readyState表示当前对象状态,分为0~4的类别,0: uninitialized, 1: loading, 2: loaded, 3: interactive, 4: complete。status表示HTTP响应状态,常见状态有200 OK,304 Not Modified,401 Unauthorized,403 Forbidden,404 Not Found,500 Internal Server Error,503 Service Unavailable。代码中认定readyState==4和status==200为正常状态。

       下面再来看一个简单的代码,当用户点击Page1~4时,相应的链接文件将会显示在My Webpage页面中。

page

<html>  <head>  <title>Ajax Sample</title>  <script type="text/javascript">  var xmlHttp=null;  try  {    xmlHttp=new XMLHttpRequest();  }  catch (e)  {    try    {      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");    }    catch (e)    {      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");    }  }  function makerequest(serverPage,objId)  {  	var obj = document.getElementById(objId);    xmlHttp.open("GET", serverPage);    xmlHttp.onreadystatechange = function()     {      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)       {         obj.innerHTML = xmlHttp.responseText;      }    }    xmlHttp.send(null);  }  </script>  <body onload="makerequest ('content1.html','hw')">    <div align="center">      <h1>My Webpage</h1>      <a href="content1.html" onclick="makerequest('content1.html','hw'); return false;">Page 1</a>       <a href="content2.html" onclick="makerequest('content2.html','hw'); return false;">Page 2</a>       <a href="content3.html" onclick="makerequest('content3.html','hw'); return false;">Page 3</a>       <a href="content4.html" onclick="makerequest('content4.html','hw'); return false;">Page 4</a>      //这里就是将要替换content1~4.html内容的位置。      <div id="hw"></div>    </div>  </body>  </html>

源代码下载:

你可能感兴趣的:(Ajax & PHP 边学边练 之一 Ajax基础)