php随笔4-基本复习-Ajax

一般使用 XML 作为接收服务器数据的格式,尽管可以使用任何格式,包括纯文本。

HTML 表单

<html>
<head>
<script src="clienthint.js"></script> 
</head>

<body>

<form> 
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>

<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

JavaScript  clienthint.js

var xmlHttp

function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML=""
  return
  }
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
var url="gethint.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

AJAX 应用程序只能运行在完整支持 XML 的 web 浏览器中。
clienthint.js

<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint=="")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint." , ".$a[$i];
      }
    }
  }
}

//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>

AJAX 可与 XML 文件进行交互式通信。
根据传入的专辑名得到专辑信息
<html>
<head>
<script src="selectcd.js"></script>
</head>

<body>

<form> 
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>

<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>

</body>
</html>

XML 文件

<CATALOG>

<CD>

<TITLE>Empire Burlesque</TITLE>

<ARTIST>Bob Dylan</ARTIST>

<COUNTRY>USA</COUNTRY>

<COMPANY>Columbia</COMPANY>

<PRICE>10.90</PRICE>

<YEAR>1985</YEAR>

</CD>

</CATALOG>

selectcd.js同上只是指向页面变化为getcd.php



getcd.php

使用 XML DOM 来加载 XML 文档 "cd_catalog.xml"。

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName(‘ARTIST‘);

for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
  {
  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
    { 
    $y=($x->item($i)->parentNode);
    }
  }
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++)
{ 
//Process only element nodes
if ($cd->item($i)->nodeType==1)
  { 
  echo($cd->item($i)->nodeName);
  echo(": ");
  echo($cd->item($i)->childNodes->item(0)->nodeValue);
  echo("<br />");
  } 
}
?>
AJAX 可用来与数据库进行交互式通信。

数据库

id FirstName LastName Age Hometown Job
1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

 

HTML 表单

<html>
<head>
<script src="selectuser.js"></script>
</head>
<body>

<form> 
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>

<p>
<div id="txtHint"><b>User info will be listed here.</b></div>
</p>

</body>
</html>



selectuser.js同上只是指向页面变化为getuser.php

PHP 页面

<?php
$q=$_GET["q"];

$con = mysql_connect(‘localhost‘, ‘peter‘, ‘abc123‘);
if (!$con)
 {
 die(‘Could not connect: ‘ . mysql_error());
 }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = ‘".$q."‘";

$result = mysql_query($sql);

echo "<table border=‘1‘>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row[‘FirstName‘] . "</td>";
 echo "<td>" . $row[‘LastName‘] . "</td>";
 echo "<td>" . $row[‘Age‘] . "</td>";
 echo "<td>" . $row[‘Hometown‘] . "</td>";
 echo "<td>" . $row[‘Job‘] . "</td>";
 echo "</tr>";
 }
echo "</table>";

mysql_close($con);
?>

AJAX Database 转 XML 实例

数据库同上

HTML 表单

上面的例子包含了一个简单的 HTML 表单,以及指向 JavaScript 的链接:

<html>
<head>
<script src="responsexml.js"></script>
</head>
<body>

<form> 
Select a User:
<select name="users" onchange="showUser(this.value)">
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>

<h2>
<span id="firstname"></span>&nbsp;<span id="lastname"></span>
</h2>

<span id="job"></span>

<div style="text-align: right">
<span id="age_text"></span>
<span id="age"></span>
<span id="hometown_text"></span>
<span id="hometown"></span>
</div>

</body>
</html>



responsexml.js

var xmlHttp

function showUser(str)
 { 
 xmlHttp=GetXmlHttpObject()
 if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
 var url="responsexml.php"
 url=url+"?q="+str
 url=url+"&sid="+Math.random()
 xmlHttp.onreadystatechange=stateChanged 
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 }

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
 xmlDoc=xmlHttp.responseXML;
 document.getElementById("firstname").innerHTML=
 xmlDoc.getElementsByTagName("firstname")[0].childNodes[0].nodeValue;
 document.getElementById("lastname").innerHTML=
 xmlDoc.getElementsByTagName("lastname")[0].childNodes[0].nodeValue;
 document.getElementById("job").innerHTML=
 xmlDoc.getElementsByTagName("job")[0].childNodes[0].nodeValue;
 document.getElementById("age_text").innerHTML="Age: ";
 document.getElementById("age").innerHTML=
 xmlDoc.getElementsByTagName("age")[0].childNodes[0].nodeValue;
 document.getElementById("hometown_text").innerHTML="<br/>From: ";
 document.getElementById("hometown").innerHTML=
 xmlDoc.getElementsByTagName("hometown")[0].childNodes[0].nodeValue;
 }
}

function GetXmlHttpObject()
 { 
 var objXMLHttp=null
 if (window.XMLHttpRequest)
  {
  objXMLHttp=new XMLHttpRequest()
  }
 else if (window.ActiveXObject)
  {
  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
 return objXMLHttp
 }


responsexml.php

<?php
header(‘Content-Type: text/xml‘);
header("Cache-Control: no-cache, must-revalidate");
//A date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

$q=$_GET["q"];

$con = mysql_connect(‘localhost‘, ‘peter‘, ‘abc123‘);
if (!$con)
 {
 die(‘Could not connect: ‘ . mysql_error());
 }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = ".$q."";

$result = mysql_query($sql);

echo ‘<?xml version="1.0" encoding="ISO-8859-1"?>
<person>‘;
while($row = mysql_fetch_array($result))
 {
 echo "<firstname>" . $row[‘FirstName‘] . "</firstname>";
 echo "<lastname>" . $row[‘LastName‘] . "</lastname>";
 echo "<age>" . $row[‘Age‘] . "</age>";
 echo "<hometown>" . $row[‘Hometown‘] . "</hometown>";
 echo "<job>" . $row[‘Job‘] . "</job>";
 }
echo "</person>";

mysql_close($con);
?>

AJAX Live Search

HTML 表单

<html>
<head>
<script src="livesearch.js"></script> 
<style type="text/css"> 
#livesearch
  { 
  margin:0px;
  width:194px; 
  }
#txt1
  { 
  margin:0px;
  } 
</style>
</head>
<body>

<form>
<input type="text" id="txt1" size="30"
onkeyup="showResult(this.value)">

<div id="livesearch"></div>
</form>

</body>
</html>

livesearch.js

var xmlHttp

function showResult(str)
{
if (str.length==0)
 { 
 document.getElementById("livesearch").
 innerHTML="";
 document.getElementById("livesearch").
 style.border="0px";
 return
 }

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }

var url="livesearch.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("livesearch").
 innerHTML=xmlHttp.responseText;
 document.getElementById("livesearch").
 style.border="1px solid #A5ACB2";
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 // Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

livesearch.php

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName(‘link‘);

//get the q parameter from URL
$q=$_GET["q"];

//lookup all links from the xml file if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
 {
 $y=$x->item($i)->getElementsByTagName(‘title‘);
 $z=$x->item($i)->getElementsByTagName(‘url‘);
 if ($y->item(0)->nodeType==1)
  {
  //find a link matching the search text
  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
   {

   if ($hint=="")
    {
    $hint="<a href=‘" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "‘ target=‘_blank‘>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   else
    {
    $hint=$hint . "<br /><a href=‘" . 
    $z->item(0)->childNodes->item(0)->nodeValue . 
    "‘ target=‘_blank‘>" . 
    $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
    }
   }
  }
 }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
 {
 $response="no suggestion";
 }
else
 {
 $response=$hint;
 }
 
//output the response
echo $response;
?>

AJAX RSS 阅读器

RSS 允许对新闻和更新进行快速浏览。

HTML 表单

<html>
<head>
<script type="text/javascript" src="getrss.js"></script>
</head>
<body>

<form> 
Select an RSS-Feed:
<select onchange="showRSS(this.value)">
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>

<p><div id="rssOutput">
<b>RSS Feed will be listed here.</b></div></p>
</body>
</html>

JavaScript 类似(略)

PHP 页面

调用 JavaScript 代码的服务器页面是名为 "getrss.php" 的 PHP 文件:

<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected
if($q=="Google")
 {
 $xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
 }
elseif($q=="MSNBC")
 {
 $xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
 }

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName(‘channel‘)->item(0);
$channel_title = $channel->getElementsByTagName(‘title‘)
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName(‘link‘)
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName(‘description‘)
->item(0)->childNodes->item(0)->nodeValue;

//output elements from "<channel>"
echo("<p><a href=‘" . $channel_link
 . "‘>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");

//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName(‘item‘);
for ($i=0; $i<=2; $i++)
 {
 $item_title=$x->item($i)->getElementsByTagName(‘title‘)
 ->item(0)->childNodes->item(0)->nodeValue;
 $item_link=$x->item($i)->getElementsByTagName(‘link‘)
 ->item(0)->childNodes->item(0)->nodeValue;
 $item_desc=$x->item($i)->getElementsByTagName(‘description‘)
 ->item(0)->childNodes->item(0)->nodeValue;

 echo ("<p><a href=‘" . $item_link
 . "‘>" . $item_title . "</a>");
 echo ("<br />");
 echo ($item_desc . "</p>");
 }
?>

AJAX 投票

HTML 表单

<html>
<head>
<script src="poll.js"></script> 
</head>
<body>

<div id="poll">
<h2>Do you like PHP and AJAX so far?</h2>

<form>
Yes: 
<input type="radio" name="vote" 
value="0" onclick="getVote(this.value)">
<br />
No: 
<input type="radio" name="vote" 
value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

文本文件

文本文件 (poll_result.txt) 中存储来自投票程序的数据。

它类似这样:

0||0

JavaScript 类似(略)

poll_vote.php

<?php
$vote = $_REQUEST[‘vote‘];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
 {
 $yes = $yes + 1;
 }
if ($vote == 1)
 {
 $no = $no + 1;
 }

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width=‘<?php echo(100*round($yes/($no+$yes),2)); ?>‘
height=‘20‘>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif" 
width=‘<?php echo(100*round($no/($no+$yes),2)); ?>‘
height=‘20‘>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。