Ajax使用

来源:互联网 发布:MOC Linux 编辑:程序博客网 时间:2024/05/17 20:35

Ajax是一个动态网页的加载方式,他可以根据需要动态的在原有网页上添加新的信息。

而不用去服务器请求新的网页,更节省资源,同时速度更快。

Ajax有固定的套路,我先举一个例子:

<html><head><script type="text/javascript">function loadXMLDoc(){var xmlhttp;var txt,x,xx,i;if (window.XMLHttpRequest)  {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();  }else  {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }  xmlhttp.onreadystatechange=function()    {    if (xmlhttp.readyState==4 && xmlhttp.status==200)     {    document.getElementById("my").innerHTML=xmlhttp.responseText;    }  }xmlhttp.open("GET","PhpMongodbText.php",true);xmlhttp.send();}</script></head><body><div id="myDiv"><h2 id="my">Let AJAX change this text</h2></div><button type="button" onclick="loadXMLDoc()">Show the Dataset</button></body></html>

这一Ajax使用通常的例子:

首先需要变量xmlhttp。

之后:

if (window.XMLHttpRequest)  {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();  }else  {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }
启动浏览器的请求,这个主要根据浏览器的版本。

xmlhttp.open("GET","PhpMongodbText.php",true);xmlhttp.send();
这个是请求需要调用的Ajax文件,可以使php也可以使asp的文件。

我们理解为一个函数就可以,调用一个有返回值的函数。

然后显示这些信息在:Id=my的的节点下面。

这里我们给出一个简单的ajax:

<?php$text = "hello the world";echo &text;?>
这样,当点击按钮后,会网页会得到text的信息hello the world。

显示在div的id=my的控件下面。

这个ajax文件时用php写的,因为php更容易一些。

这样我们可以通过php调用数据库信息显示在网页中。

新浪微博,foursquare等网站现在都采用这种方式去更新网页。

在给出一个php调用mongodb的ajax程序:

<?php//$text = "hello the world";//echo $text;// connect$dburl = 'localhost';$port= '27017';  $m = new Mongo();// select a database$db = $m->FourS2;// select a collection (analogous to a relational database's table)$collection = $db->Foursquare;// add a record//$obj = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );//$collection->insert($obj);// add another record, with a different "shape"//$obj = array( "title" => "XKCD", "online" => true );//$collection->insert($obj);// find everything in the collection$cursor = $collection->find();// iterate through the resultsecho ($cursor);?>


参考资料:

http://www.w3school.com.cn/ajax/ajax_asp_php.asp