In this example, the effects are as follows: when selecting a programming language from the select drop-down box, different function API descriptions are requested asynchronously based on different options. For more information, see
Ajax greatly improves user experience, which is essential for Web and an essential skill for front-end developers.
In this example, when selecting a programming language from the select drop-down box, asynchronous requests are requested for different function API descriptions based on different options. This feature is common in web applications.
Let's take a look at the structure of $. get ().
The Code is as follows:
$. Get (url, [, data], [, callback] [, type])
// Url: the URL of the requested HTML page;
// Data (Optional). The key/value data sent to the server is appended to the request URL as QueryString;
// Callback (optional): The callback function when the load is successful (this method is called only when the Response returns success;
// Type (optional): the format of the content returned by the server, including xml, html, script, json, text, and _ default.
First, create the examplDB database and create the language and functions tables. The SQL statements are as follows:
The Code is as follows:
Create table if not exists language (
Id int (3) not null AUTO_INCREMENT,
LanguageName varchar (50) not null,
Primary key (id ));
Create table if not exists functions (
Id int (3) not null AUTO_INCREMENT,
LanguageId int (11) not null,
FunctionName varchar (64) not null,
Summary varchar (128) not null, // function Overview
Example text not null, // example
Primary key (id ));
The following is the SQL statement for inserting data.
The Code is as follows:
Insert into language (id, languageName) VALUES
(1, 'php '),
(2, 'jquery ');
Insert into functions (id, languageId, functionName, summary, example) VALUES
(1, 1, 'simplexml _ load_file ', 'interprets an XML file into an object',' $ xml = simplexml_load_file (''test. xml ''); \ r \ nprint_r ($ xml); \ r \ n '),
(2, 1, 'array _ push', 'push one or more elements onto the end of array', '$ arrPets = array ('Dog '', ''cat'', ''fish ''); \ r \ narray_push ($ arrPets, ''bird'', ''rat ''); \ r \ n '),
(3, 1, 'uccfirst', 'Make a string ''s first character uppercase',' $ message = ''have a nice day; \ r \ n $ message = ucfirst ($ message); // output: Have A Nice Day \ r \ n '),
(4, 1, 'mail', 'used to send address', '$ message = "Example message for mail "; \ r \ nif (mail (''test @ test.com '', ''test Subject'', $ message )) \ r \ n {\ r \ n echo ''mail sent ''; \ r \ n} \ r \ nelse \ r \ n {\ r \ n echo ''sending of mail failed ''; \ r \ n} \ r \ n '),
(5, 2, '$. get', 'Load data from the server using a HTTP get request. ',' $. ajax ({\ r \ n url: url, \ r \ n data: data, \ r \ n success: success, \ r \ n dataType: dataType \ r \ n}); \ r \ n '),
(6, 2, 'hover ', 'hover method accepts 2 functions as parameters which execute alternativelt when mouse enters and leaves an element. ',' $ (selector ). hover (\ r \ nfunction () \ r \ n {\ r \ n // executes on mouseenter \ r \ n}, \ r \ nfunction () \ r \ n {\ r \ n // executes on mouseleave \ r \ n });'),
(7, 2, 'bind', 'Attach a handler to an event for the elements. ',' $ (element ). bind (''click'', function () \ r \ n {\ r \ n alert (''click happened'); \ r \ n }); \ r \ n '),
(8, 2, 'jquery. data', 'store arbitrary data associated with the specified element. ', 'jquery. data (element, key, value );'),
(9, 1, 'add class', 'adds a class', '('P'). addClass (''myclass yourclass '');');
They are all relatively simple SQL operations, and can be encoded after everything is ready. There are a total of two script files, one index. php and one results. php, which are used to process requests. Compile index. php first.
The Code is 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
{
$ Query = 'select * FROM language '; // The core code is started here. They are all very simple statements. They are mainly used to obtain records in the language and output them to the SELECT option cyclically.
If ($ result = $ mysqli-> query ($ query ))
{
If ($ result-> num_rows> 0)
{
?>
<P>
Select a region AE
<Select id = "selectLanguage">
<Option value = ""> select </option>
<? Php
While ($ row = $ result-> fetch_assoc () // use the programming language id as the option value and language as the option.
{
?>
<Option value = "<? Php echo $ row ['id'];?> "> <? Php echo $ row ['your agename'];?> </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 ($ (this). val () = '') return;
$. Get (
'Ults. php ',
{Id: $ (this). val ()},
Function (data ){
Certificate ('{result'}.html (data );
}
);
});
});
</Script>
</Body>
</Html>
Introduce jquery and add the change event handler to # selectLanguage, and put it before the end of the body in index. php.
The Code is as follows:
<Script src = "scripts/jquery. js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ('# SelectLanguage'). change (function (){
If ($ (this). val () = '') return;
$. Get (
'Ults. php ',
{Id: $ (this). val ()},
Function (data ){
Certificate ('{result'}.html (data );
}
);
});
});
</Script>
The following is results. php. It connects to the database first, obtains index. php, sends it to the id, selects the corresponding programming language record in the database according to the id, and places each record to the ul list.
The Code is as follows:
<? Php
$ Mysqli = new mysqli ('localhost', 'root', 'passwd', 'exampledb'); // Use Your Database Password to rewrite passwd.
$ ResultStr = '';
$ Query = 'select functionName, summary, example FROM functions where your ageid = '. $ _ GET ['id']; // $ _ GET ['id'] is the index. $. id sent by get ()
If ($ result = $ mysqli-> query ($ query ))
{
If ($ result-> num_rows> 0)
{
$ ResultStr. = '<ul> ';
While ($ row = $ result-> fetch_assoc () // similar to the index. php statement, the record is obtained from the database first, and then formatted and 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;
?>