Menu Close

PHP & AJAX指南,AJAX自动搜索源码,Ajax XML 示例

AJAX 是什么?

  • AJAX 代表异步 JavaScript 和 XML。AJAX 是一种新技术,它是在 XML、HTML、CSS 和 Java 帮助下可以创建更好、更快、交互式 web 应用程序的脚本语言。
  • 传统 web 应用程序使用同步请求从服务器传送信息。这意味着你填写表格,点击提交,获得定向到一个新的从服务器获取信息页面。
  • 使用 AJAX 提交按钮被按下时,JavaScript 将发送一个请求到服务器,解释结果和更新当前屏幕。在纯粹意义上,用户甚至不会知道什么时候把请求传送到服务器上。

PHP and AJAX 例子

明确说明使用 AJAX 和 PHP 是非常容易的从数据库中获取信息,我们要在 “ajax.html” 建立动态 MySQL 查询和显示结果。

但在我们继续进行工作之前,让 AJAX 做下工作。可以使用以下命令创建一个表。

注释:我们确保您有足够的权限来执行 MySQL 操作:

    CREATE TABLE `ajax_example` (
      `name` varchar(50) NOT NULL,
      `age` int(11) NOT NULL,
      `sex` varchar(1) NOT NULL,
      `wpm` int(11) NOT NULL,
      PRIMARY KEY  (`name`)
    ) 

现在使用以下 SQL 语句将以下数据转储到此表:

    INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
    INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
    INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
    INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
    INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
    INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

客户端 HTML 文件

现在可以让我们的客户端 HTML 文件创建 ajax。如下是 html 和它的代码:

s<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!

 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

注意:查询中传递变量的方式必须遵循 HTTP 标准和形式。

    URL?variable1=value1;&variable2=value2;

服务器端 PHP 文件

现在你的客户端脚本已经准备好了。现在我们必须编写服务器端脚本将获取的 age, wpm 和 sex 从数据库取出并将其发送回客户端。把以下代码放入到 “ajax-example.php” 文件中

<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
    //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
    //Select Database
mysql_select_db($dbname) or die(mysql_error());
    // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
    // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
    //build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
    $query .= " AND age <= $age";
if(is_numeric($wpm))
    $query .= " AND wpm <= $wpm";
    //Execute query
$qry_result = mysql_query($query) or die(mysql_error());

    //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
    $display_string .= "<tr>";
    $display_string .= "<td>$row[name]</td>";
    $display_string .= "<td>$row[age]</td>";
    $display_string .= "<td>$row[sex]</td>";
    $display_string .= "<td>$row[wpm]</td>";
    $display_string .= "</tr>";

}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

PHP – Ajax Search

Ajax is used to communicate with web pages and web servers. Below example demonstrate a search field using with Ajax.

<html>
   <head>
      
      <style>
         span {
            color: green;
         }
      </style>
      
      <script>
         function showHint(str) {
            if (str.length == 0) {
               document.getElementById("txtHint").innerHTML = "";
               return;
            }else {
               var xmlhttp = new XMLHttpRequest();
					
               xmlhttp.onreadystatechange = function() {
                  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                     document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                  }
               }
               xmlhttp.open("GET", "php_ajax.php?q=" + str, true);
               xmlhttp.send();
            }
         }
      </script>
      
   </head>
   <body>
      
      <p><b>Search your favourite tutorials:</b></p>
      
      <form>
         <input type = "text" onkeyup = "showHint(this.value)">
      </form>
      
      <p>Entered Course name: <span id="txtHint"></span></p>
   
   </body>
</html>

Above code opens a file, name called as php_ajax.php by using with GET method, so we need to create a file, name called as php_ajax.php in the same directory and out put will be attached with txtHint.

READ  PHP数组

php_ajax.php

It contained array of course names and it returns the value to web browser.

<?php
   // Array with names
   $a[] = "Android";
   $a[] = "B programming language";
   $a[] = "C programming language";
   $a[] = "D programming language";
   $a[] = "euphoria";
   $a[] = "F#";
   $a[] = "GWT";
   $a[] = "HTML5";
   $a[] = "ibatis";
   $a[] = "Java";
   $a[] = "K programming language";
   $a[] = "Lisp";
   $a[] = "Microsoft technologies";
   $a[] = "Networking";
   $a[] = "Open Source";
   $a[] = "Prototype";
   $a[] = "QC";
   $a[] = "Restful web services";
   $a[] = "Scrum";
   $a[] = "Testing";
   $a[] = "UML";
   $a[] = "VB Script";
   $a[] = "Web Technologies";
   $a[] = "Xerox Technology";
   $a[] = "YQL";
   $a[] = "ZOPL";
   
   $q = $_REQUEST["q"];
   $hint = "";
   
   if ($q !== "") {
      $q = strtolower($q);
      $len = strlen($q);
      
      foreach($a as $name) {
		
         if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
               $hint = $name;
            }else {
               $hint .= ", $name";
            }
         }
      }
   }
   echo $hint === "" ? "Please enter a valid course name" : $hint;
?>

It will produce the following result −

Ajax Search

PHP – Ajax XML 解析器

Ajax XML 示例

使用 Ajax,我们可以从本地目录和服务器解析 xml,下面的示例演示如何使用 Web 浏览器解析 xml。

<html>
   <head>
   
      <script>
         function showCD(str) {
            if (str == "") {
               document.getElementById("txtHint").innerHTML = "";
               return;
            }
            
            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("txtHint").innerHTML = xmlhttp.responseText;
               }
            }
            xmlhttp.open("GET","getcourse.php?q="+str,true);
            xmlhttp.send();
         }
      </script>
   
   </head>
   <body>
      
      <form>
         Select a Course:
         <select name = "cds" onchange = "showCD(this.value)">
            <option value = "">Select a course:</option>
            <option value = "Android">Android </option>
            <option value = "Html">HTML</option>
            <option value = "Java">Java</option>
            <option value = "Microsoft">MS technologies</option>
         </select>
      </form>
      
      <div id = "txtHint"><b>Course info will be listed here...</b></div>
      
   </body>
</html>

上面的示例将使用 GET 方法调用 getcourse.php。 getcourse.php 文件加载catalog.xml。 getcourse.php 如下所示 –

<?php
   $q = $_GET["q"];
   
   $xmlDoc = new DOMDocument();
   $xmlDoc->load("catalog.xml");
   
   $x = $xmlDoc->getElementsByTagName('COURSE');
   
   for ($i = 0; $i<=$x->length-1; $i++) {
      =
      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++) {
      if ($cd->item($i)->nodeType == 1) {
         echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
         echo($cd->item($i)->childNodes->item(0)->nodeValue);
         echo("<br>");
      }
   }
?>

Catalog.xml

具有课程列表和详细信息的 XML 文件。该文件由 getcourse.php 访问.

<CATALOG>
   <SUBJECT>
      <COURSE>Android</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>TutorialsPoint</COMPANY>
      <PRICE>$10</PRICE>
      <YEAR>2015</YEAR>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>Html</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>TutorialsPoint</COMPANY>
      <PRICE>$15</PRICE>
      <YEAR>2015</YEAR>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>Java</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>TutorialsPoint</COMPANY>
      <PRICE>$20</PRICE>
      <YEAR>2015</YEAR>
   </SUBJECT>
   
   <SUBJECT>
      <COURSE>Microsoft</COURSE>
      <COUNTRY>India</COUNTRY>
      <COMPANY>TutorialsPoint</COMPANY>
      <PRICE>$25</PRICE>
      <YEAR>2015</YEAR>
   </SUBJECT>
</CATALOG>

它将产生以下结果 –

READ  编程语言共有几种?

XML Parser

PHP – Ajax 自动完成搜索

自动完成搜索

当您在字段中输入数据时,自动完成搜索框会提供建议。这里我们使用 xml 来调用自动完成建议。下面的示例演示如何使用 php 使用自动完成文本框。

 

Index 页面

index页面应如下所示 –

<html>
   <head>
      
      <style>
         div {
            width:240px;
            color:green;
         }
      </style>
      
      <script>
         function showResult(str) {
			
            if (str.length == 0) {
               document.getElementById("livesearch").innerHTML = "";
               document.getElementById("livesearch").style.border = "0px";
               return;
            }
            
            if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
            }else {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            
            xmlhttp.onreadystatechange = function() {
				
               if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                  document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
                  document.getElementById("livesearch").style.border = "1px solid #A5ACB2";
               }
            }
            
            xmlhttp.open("GET","livesearch.php?q="+str,true);
            xmlhttp.send();
         }
      </script>
      
   </head>
   <body>
      
      <form>
         <h2>Enter Course Name</h2>
         <input type = "text" size = "30" onkeyup = "showResult(this.value)">
         <div id = "livesearch"></div>
         <a href = "http://www.tutorialspoint.com">More Details </a>
      </form>
      
   </body>
</html>

livesearch.php

它用于从 xml 文件中调用数据,并将结果发送到 Web 浏览器。

<?php
   $xmlDoc = new DOMDocument();
   $xmlDoc->load("autocomplete.xml");
   $x = $xmlDoc->getElementsByTagName('link');
   $q = $_GET["q"];
   
   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) {
            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>";
               }
            }
         }
      }
   }
	
   if ($hint == "") {
      $response = "Please enter a valid name";
   }else {
      $response = $hint;
   }
   echo $response;
?>

autocomplete.xml

它包含自动完成数据,并由 livesearch.php 基于标题字段和 Url 字段访问

<pages>

   <link>
      <title>android</title>
      <url>http://www.tutorialspoint.com/android/index.htm</url>
   </link>

   <link>
      <title>Java</title>
      <url>http://www.tutorialspoint.com/java/index.htm</url>
   </link>

   <link>
      <title>CSS </title>
      <url>http://www.tutorialspoint.com/css/index.htm</url>
   </link>

   <link>
      <title>angularjs</title>
      <url>http://www.tutorialspoint.com/angularjs/index.htm </url>
   </link>

   <link>
      <title>hadoop</title>
      <url>http://www.tutorialspoint.com/hadoop/index.htm </url>
   </link>

   <link>
      <title>swift</title>
      <url>http://www.tutorialspoint.com/swift/index.htm </url>
   </link>

   <link>
      <title>ruby</title>
      <url>http://www.tutorialspoint.com/ruby/index.htm </url>
   </link>

   <link>
      <title>nodejs</title>
      <url>http://www.tutorialspoint.com/nodejs/index.htm </url>
   </link>

</pages>

它将产生以下结果 –

Autocomplete Search

PHP – Ajax RSS Feed 示例

RSS

Really Simple Syndication is used to publish often updated information from website like audio, video, images, etc. We can integrate RSS feeds to a website by using Ajax and php. This code demonstrates how to show RSS feeds in our site.

READ  PHP 文件上传

Index.html

Index page should be as follows −

<html>
   <head>
      
      <script>
         function showRSS(str) {
            if (str.length == 0) { 
               document.getElementById("output").innerHTML = "";
               return;
            }
         
            if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();
            }else {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
               if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                  document.getElementById("output").innerHTML = xmlhttp.responseText;
               }
            }
            
            xmlhttp.open("GET","rss.php?q="+str,true);
            xmlhttp.send();
         }
      </script>
      
   </head>
   
   <body>
      <p>Please Select an option to get RSS:</p>
      
      <form>
         <select onchange = "showRSS(this.value)">
            <option value = "">Select an RSS-feed:</option>
            <option value = "cnn">CNN</option>
            <option value = "bbc">BBC News</option>
            <option value = "pc">PC World</option>
         </select>
      </form>
      <br>
      
      <div id = "output">RSS-feeds</div>
      
   </body>
</html>

rss.php

rss.php has contained syntax about how to get access to rss feeds and return rss feeds to web pages.

<?php
   $q = $_GET["q"];
   
   if($q == "cnn") {
      $xml = ("http://rss.cnn.com/rss/cnn_topstories.rss");
   }elseif($q == "bbc") {
      $xml = ("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml");
   }elseif($q = "pcw"){
      $xml = ("http://www.pcworld.com/index.rss");
   }
	
   $xmlDoc = new DOMDocument();
   $xmlDoc->load($xml);
   
   $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;
   
   echo("<p><a href = '" . $channel_link . "'>" . 
      $channel_title . "</a>");
   echo("<br>");
   echo($channel_desc . "</p>");
   
   $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>");
   }
?>

It will produce the following result −

RSS Feed Example

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in PHP教程

Related Posts