Diferència entre revisions de la pàgina «Solució exercici6-ajax»

De wikiserver
Dreceres ràpides: navegació, cerca
(Es crea la pàgina amb «<source lang="java"> <!DOCTYPE html> <html> <head> <script> function showHint(str) { var xmlhttp; if (str.length==0) { document.getElementById("txtHint").innerHTML=…».)
 
Línia 1: Línia 1:
 +
 
<source lang="java">
 
<source lang="java">
  
Línia 56: Línia 57:
 
</source>
 
</source>
  
 +
 +
//fitxer php
 
<source lang="java">
 
<source lang="java">
 
<?php
 
<?php

Revisió del 16:35, 17 març 2015

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  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)
    {
		//alert(xmlhttp.responseText);
    	//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
		var chunk = xmlhttp.responseText.split("*");
		txt = "<ul>";
		for (i in chunk) {
			txt += "<li>"+chunk[i]+"</li>";
		}
		txt += "</ul>";
		setTimeout(function(){document.getElementById("txtHint").innerHTML= txt;},3000);

    } else {
		document.getElementById("txtHint").innerHTML="<img src='img/ajax-loader.gif' />";
	}
  }
xmlhttp.open("GET","php/gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>


//fitxer php

<?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";
$a[]="Maria";
$a[]="Pere";
$a[]="Rita";
$a[]="Jordi";
$a[]="Anna";
$a[]="Núria";

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

// lookup all hints from array if $q is different from ""
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"; }
      }
    }
  }

// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>