Exemple PHP - AJAX Live Search


Exemple PHP - AJAX Live Search

AJAX peut être utilisé pour créer des recherches plus conviviales et interactives.

AJAX Live Search

L'exemple suivant démontre une recherche en direct, où vous obtenez des résultats de recherche pendant que vous tapez.
Live search a de nombreux avantages par rapport à la recherche traditionnelle:
  • Les résultats sont présentés que vous tapez
  • Résultats étroites que vous continuer la saisie
  • Si les résultats devenu trop étroit, effacer les caractères à voir un plus large résultat
Rechercher une page W3Schools dans le champ de saisie ci-dessous:
Les résultats dans l'exemple ci-dessus se trouvent dans un fichier XML ( links.xml ). Pour faire ce petit exemple simple et, seulement six résultats sont disponibles.

Exemple Explication - La page HTML

Quand un utilisateur tape un caractère dans le champ de saisie ci-dessus, la fonction "showResult ()" est exécuté. La fonction est déclenchée par l'"onkeyup" événement:
<html>
<head>
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  {
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  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("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>
<input type="text" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>

</body>
</html>
Explication du code source:
Si le domaine d'entrée est vide (str.length == 0), la fonction efface le contenu de l'espace réservé livesearch et sort de la fonction.
Si le champ de saisie n'est pas vide, le showResult () exécute ce qui suit:
  • Créer un objet XMLHttpRequest
  • Création de la fonction à exécuter lorsque la réponse du serveur est prêt
  • Envoyer la demande hors d'un fichier sur le serveur
  • Avis qu 'un paramètre (q) est ajouté à l'URL (avec le contenu du champ de saisie)

Le fichier PHP

La page sur le serveur appelé par le code JavaScript ci-dessus est un fichier PHP appelé "livesearch.php".
Le code source dans "livesearch.php" recherche d'un fichier XML pour les titres correspondant à la chaîne de recherche et retourne le résultat:
<?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;
?>
S'il ya un texte envoyé à partir du JavaScript (strlen ($ q)> 0), ce qui suit se produit:
  • Charger un fichier XML dans un nouvel objet XML DOM
  • Boucle à travers tous les éléments pour trouver des correspondances <title> dans le texte envoyé à partir du JavaScript
  • Définit l'URL correcte et le titre dans le "$ response" variable. Si plus d'une correspondance est trouvée, tous les matches sont ajoutés à la variable
  • Si aucune correspondance n'est trouvée, la variable de réponse $ est réglé sur "aucune suggestion"

21 commentaires:

  1. Thank you, I've just been searching for information about this subject for a while and yours is the greatest I have discovered so far. However, what concerning the conclusion? Are you sure about the source?
    engineered hardwood floors

    Also visit my web page: cleaning hardwood floors

    ReplyDelete
  2. When some one searches for his vital thing,
    therefore he/she wants to be available that in detail, so that thing is maintained over here.



    Also visit my webpage; hardwood flooring

    ReplyDelete
  3. When some one searches for his vital thing, therefore he/she wants to be available that
    in detail, so that thing is maintained over here.


    Here is my web page ... hardwood flooring
    Also see my web site > http://www.flooranddecoroutlets.com/hardwood-solid.html

    ReplyDelete
  4. Howdy! This post couldn't be written any better! Looking through this article reminds me of my previous roommate! He continually kept talking about this. I am going to forward this article to him. Fairly certain he will have a great read. Many thanks for sharing!

    my homepage - affordable hardwood flooring

    ReplyDelete
  5. Keep this going please, great job!

    Look into my web site ... http://www.flooranddecoroutlets.com/hardwood-solid.html

    ReplyDelete
  6. Hello! This is kind of off topic but I need some guidance from an established blog.

    Is it very hard to set up your own blog? I'm not very techincal but I can figure things out pretty quick. I'm thinking about setting up my own but I'm not sure where to begin. Do you have any ideas or suggestions? Cheers

    Feel free to visit my web page ... hardwood floors
    My site: hardwood flooring

    ReplyDelete
  7. Way cool! Some very valid points! I appreciate you penning this post and
    also the rest of the website is really good.

    Also visit my homepage :: nail fungus zetaclear
    my web site - zetaclear reviews

    ReplyDelete
  8. Great web site you've got here.. It's difficult to find high quality
    writing like yours these days. I seriously appreciate individuals
    like you! Take care!!

    My blog maid service

    ReplyDelete
  9. Have you ever thought about creating an ebook or guest authoring on other sites?
    I have a blog centered on the same ideas you discuss and would really like
    to have you share some stories/information. I know my
    visitors would enjoy your work. If you are even remotely interested, feel free to send me
    an e mail.

    Here is my web site - cleaning.com

    ReplyDelete
  10. Way cool! Some extremely valid points! I appreciate you penning this post and also the rest of the site is also very good.


    My weblog; http://firewallgroupsocial.atwebpages.com

    ReplyDelete
  11. Hello, all is going fine here and ofcourse every one is sharing facts, that's genuinely excellent, keep up writing.

    Feel free to visit my blog post - hair loss prevention product

    ReplyDelete
  12. I visited several blogs however the audio feature for audio songs present at this site is truly
    fabulous.

    Have a look at my website natural hair
    Also see my web page - youthbook.com.pk

    ReplyDelete
  13. Your way of explaining all in this paragraph is genuinely fastidious, every one
    be able to effortlessly know it, Thanks a lot.


    My blog - wartrol scam

    ReplyDelete
  14. Valuable information. Lucky me I found your web site by accident, and I'm shocked why this accident didn't came about earlier!
    I bookmarked it.

    Feel free to surf to my homepage - Sac Louis Vuitton

    ReplyDelete
  15. I have read so many posts on the topic of the blogger lovers however this paragraph is in fact a good
    post, keep it up.

    My webpage http://zetaclearreviews-hq.blogspot.com

    ReplyDelete
  16. Your mode of describing all in this paragraph
    is truly fastidious, all be capable of easily be aware of it, Thanks a lot.


    Feel free to surf to my website - resources

    ReplyDelete
  17. Hello there! I know this is kinda off topic but I was wondering which blog platform are
    you using for this site? I'm getting sick and tired of Wordpress because I've had issues with
    hackers and I'm looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

    Feel free to visit my site Tory Burch Outlet

    ReplyDelete
  18. It's a shame you don't have a donate button! I'd without a doubt donate to this fantastic blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this website
    with my Facebook group. Chat soon!

    My weblog: Sac Louis Vuitton

    ReplyDelete
  19. Good post. I am dealing with a few of these issues as
    well..

    Here is my page; Air Max :: ::

    ReplyDelete
  20. My brother suggested I may like this website.
    He used to be entirely right. This submit actually made my day.
    You cann't imagine just how a lot time I had spent for this info! Thank you!

    Review my weblog; Louis Vuitton Pas Cher

    ReplyDelete

HELLO VISITORS THANKS FOR YOUR VISIT AND COMMENT