Use $.get () to asynchronously request data from a database based on different options

Source: Internet
Author: User
Tags bind html page

  This example implements the effect that when you select a programming language from the Select Drop-down box, depending on the options, asynchronous requests for different function APIs are described, and the required friends can refer to the following

Ajax has greatly improved the user experience, which is essential for web2.0 and is an essential skill for front-end developers.     This is the case when you choose a programming language from the Select Drop-down box and, depending on the options, asynchronous requests a different function API description. This functionality is common in Web applications today.     Let's take a look at the structure of $.get ()     code as follows: $.get (URL, [, Data], [, Callback] [, type])  //url: URL address of the requested HTML page;  //data (optional), key/value data sent to the server is appended to the request URL as QueryString; //callback (optional): The callback function when the load succeeds (optional) When the response return state is success; //type (optionally): Server-side return content format, including Xml,html,script,json,text and _default     First create EXAMPLDB database, build language and functions tables, SQL as follows     code as follows: Create TABLE IF not EXISTS language (  I d Int (3) not NULL auto_increment,  languagename varchar (m) not null,  PRIMARY KEY (ID);    CREATE TA BLE IF not EXISTS functions (  ID int (3) not NULL auto_increment,  LanguageID Int (one) not null,  Me varchar not null,  summary varchar (128) is not NULL,//Feature Overview   example text NOT NULL,//Example   PRIMARY KEY ( ID);    Below is the sql    code for inserting data as follows: INSERT INTO language(ID, LanguageName) values  (1, ' PHP '),  (2, ' jQuery ');    INSERT into functions (ID, LanguageID, functionname, summary, E Xample) values  (1, 1, ' simplexml_load_file ', ' interprets an XML file to an object ', ' $xml = simplexml_load_file (' ' Test.xml '); Rnprint_r ($xml); Rn '),  (2, 1, ' Array_push ', ' push one or more elements onto ' "End of Array ', ' $arrPets = Array (' Dog ', ' Cat ', ' ' Fish '); Rnarray_push ($arrPets, ' Bird ', ' Rat '), RN '),  (3, 1, ' ucfirst ', ' Make a stri Ng ' s-character uppercase ', ' $message = ' have a nice day;rn$message = Ucfirst ($message); Output:have A Nice Dayrn '),  (4, 1, ' mail ', ' used to send email ', ' $message = ' Example message for mail '; Rnif (mai L (' test@test.com ', ' Test Subject ', $message)) Rn{rn Echo ' Mail sent '; Rn}rnelsern{rn Echo ' Sending of mail failed '; Rn}rn '),  (5, 2, ' $.get ', ' Load data from the ' server using a HTTP GET request. ', ' $.ajax ({rn Url:url,rn data:data,r N Success:success,rn dataType:Datatypern}); Rn '),  (6, 2, ' hover ', ' hover method accepts 2 functions as parameters which execute alternativelt when Mouse enters and leaves a element. ', ' $ (selector). Hover (Rnfunction () rn{rn//executes on mouseenterrn},rnfunction () rn{ Rn//executes on Mouseleavern}):,  (7, 2, ' bind ', ' Attach a handler to an event for the elements. ', ' $ (element). Bind (' click ', Function () Rn{rn alert (' click happened '); RN}); Rn '),  (8, 2, ' jquery.data ', ' Store arbitrary Data Assoc Iated with the specified element. ', ' jquery.data (element, key, value); ',  (9, 1, ' Add Class ', ' Adds a class ', ' (' P ') '). addclass (' MyClass yourclass ');     are simpler SQL operations and can be coded after everything is ready. A total of two script files, a index.php, a results.php for processing requests, first write index.php    code as follows: <! DOCTYPE html>  <html>  <head>  <title></title>  <style type= "text/ CSS ">  body {font-family:" Trebuchet MS ", Verdana, Arial; width:600px;}   DIV {background-color: #f5f5dc;}  </style>  <script type= "Text/javascript" src= "Jquery.js" ></script>  </head>   <body>  <?php  $mysqli = new mysqli (' localhost ', ' root ', ' passwd ', ' exampledb '); Change passwd to your database password   if (Mysqli_connect_errno ())   {  die (' Unable to connect '); } -else  {& nbsp $query = ' SELECT * from language '; This starts with the core code, which is a very simple statement, mainly to get records in language, and then loop output to select options   if ($result = $mysqli->query ($query))   {  if ($result->num_rows > 0)   { ?>  <p>  Select a languae  <select id= "Selectla Nguage ">  <option value=" ">select</option>  <?php  while ($row = $result->fetch_ Assoc ())//The ID of the programming language is the value of option, with the language as an option.   { ?>  <option value= "<?php echo $row [' id '];? > "><?php echo $row [' LanguageName '];?></option>  <?php } ?>  </ select>  </p>  <p id= ResUlt "></p>  <?php }  else  {  echo ' No records found '; }  $result-> Close (); }  else  {  echo ' Error in query: $query. ' $mysqli->error; } }  $mysqli->close (); ?>    <script type= "text/ JavaScript ">  $ (function () {  $ (' #selectLanguage '). Change (function () {  if ($ (). val () = =") return;  $.get (  ' results.php ',  {ID: $ (this). Val ()},  function (data) {  $ (' #result '). HTML ( Data); } ); }); };  </script>  </body>  </html>    Introduce jquery, add a Change event handler to #selectlanguage, and place it in index.php before the body ends     code as follows: <script src= "Scripts/jquery.js" ></script>  <script type= "Text/javascript" >  $ (function () {  $ (' #selectLanguage '). Change (function () {  if ($ (). val () = ") return;  $.get (  ' results.php ',  {ID: $ (this). Val ()},& nbsp FUnction (data) {  $ (' #result '). HTML (data); } ); }); });  </script>    Here's the results.php. It connects to the database first, then obtains index.php sends to the ID, chooses the corresponding programming language record according to the ID in the database, and puts each record in the UL list     code as follows: <?php  $mysqli = new mysqli (' localhost ', ' root ', ' passwd ', ' exampledb '); Here also use your database password to rewrite passwd  $resultStr = ';  $query = ' SELECT functionname, Summary, example from functions where l Anguageid = '. $_get[' id ']; $_get[' id ' is the id  if ($result = $mysqli->query ($query)) sent with $.get () in index.php   {  if ($result-> Num_rows > 0)   {  $resultStr. = ' <ul> ';  while ($row = $result->fetch_assoc ())// Similar to the index.php statement, you get the records from the database first, then format the output   {  $resultStr. = ' <li><strong> ' $row [' functionname ']. ' </strong>-'. $row [' Summary '];  $resultStr. = ' <div><pre> '. $row [' example ']. ' </pre></div> '. ' </li> '; }  $resultStr. = ' </ul> '; }  else  {  $reSultstr = ' Nothing found '; } }  echo $resultStr; ?>   
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.