主頁(yè) > 知識(shí)庫(kù) > 使用$.get()根據(jù)選項(xiàng)的不同從數(shù)據(jù)庫(kù)異步請(qǐng)求數(shù)據(jù)

使用$.get()根據(jù)選項(xiàng)的不同從數(shù)據(jù)庫(kù)異步請(qǐng)求數(shù)據(jù)

熱門標(biāo)簽:團(tuán)購(gòu)網(wǎng)站 銀行業(yè)務(wù) Linux服務(wù)器 Mysql連接數(shù)設(shè)置 科大訊飛語(yǔ)音識(shí)別系統(tǒng) 電子圍欄 阿里云 服務(wù)器配置
Ajax極大地改善了用戶體驗(yàn),對(duì)于web2.0來(lái)說(shuō)必不可少,是前端開發(fā)人員必不可少的技能。

這個(gè)例子是這樣的,當(dāng)從select下拉框選擇編程語(yǔ)言時(shí)時(shí),根據(jù)選項(xiàng)的不同,異步請(qǐng)求不同的函數(shù)API描述。這種功能在現(xiàn)在web應(yīng)用程序中是及其常見的。

我們先來(lái)看一下$.get()的結(jié)構(gòu)
復(fù)制代碼 代碼如下:

$.get(url, [, data], [, callback] [, type])
//url:請(qǐng)求的HTML頁(yè)的URL地址;
//data(可選),發(fā)送至服務(wù)器的key/value數(shù)據(jù)作為QueryString附加到請(qǐng)求URL中;
//callback(可選):載入成功時(shí)的回調(diào)函數(shù)(只有當(dāng)Response的返回狀態(tài)是success才調(diào)用該方法;
//type(可選):服務(wù)器端返回內(nèi)容格式,包括xml,html,script,json,text和_default

首先創(chuàng)建examplDB數(shù)據(jù)庫(kù),建立language和functions表,SQL如下
復(fù)制代碼 代碼如下:

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, //功能概述
example text NOT NULL, //舉例
PRIMARY KEY (id));

下面是插入數(shù)據(jù)的SQL
復(fù)制代碼 代碼如下:

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, 'ucfirst', '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 email', '$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'');');

都是比較簡(jiǎn)單的SQL操作,一切準(zhǔn)備就緒后就可以編碼了。總共有兩個(gè)腳本文件,一個(gè)index.php,一個(gè)results.php用于處理請(qǐng)求,先編寫index.php
復(fù)制代碼 代碼如下:

!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');//將passwd改為你的數(shù)據(jù)庫(kù)密碼
if (mysqli_connect_errno())
{
die('Unable to connect');
}
else
{
$query = 'SELECT * FROM language'; //這里開始是核心代碼,都是很簡(jiǎn)單的語(yǔ)句,主要是在language中取得記錄,然后循環(huán)輸出到select選項(xiàng)
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
p>
Select a languae
select id="selectLanguage">
option value="">select/option>
?php
while($row = $result->fetch_assoc()) //以編程語(yǔ)言的id作為option的value,以語(yǔ)言作為選項(xiàng)。
{
?>
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($(this).val() == '') return;
$.get(
'results.php',
{id: $(this).val()},
function(data) {
$('#result').html(data);
}
);
});
});
/script>
/body>
/html>

引入jquery,給#selectLanguage添加change事件處理程序,并放在index.php中body結(jié)束前
復(fù)制代碼 代碼如下:

script src="scripts/jquery.js">/script>
script type="text/javascript">
$(function() {
$('#selectLanguage').change(function() {
if($(this).val() == '') return;
$.get(
'results.php',
{id: $(this).val()},
function(data) {
$('#result').html(data);
}
);
});
});
/script>

下面就是results.php了。它先連接到數(shù)據(jù)庫(kù),然后取得index.php發(fā)送到id,根據(jù)id在數(shù)據(jù)庫(kù)里選擇相應(yīng)的編程語(yǔ)言記錄,并將每條記錄放到ul列表中
復(fù)制代碼 代碼如下:

?php
$mysqli = new mysqli('localhost', 'root', 'passwd', 'exampledb'); //這里也要用你的數(shù)據(jù)庫(kù)密碼改寫passwd
$resultStr = '';
$query = 'SELECT functionName, summary, example FROM functions where languageId ='.$_GET['id']; //$_GET['id']就是index.php中用$.get()發(fā)送的id
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
$resultStr .= 'ul>';
while($row = $result->fetch_assoc()) //和index.php的語(yǔ)句差不多,也是先從數(shù)據(jù)庫(kù)取得記錄,然后格式化輸出
{
$resultStr .= 'li>strong>'.$row['functionName'].'/strong>-'.$row['summary'];
$resultStr .= 'div>pre>'.$row['example'].'/pre>/div>'.'/li>';
}
$resultStr .= '/ul>';
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>

現(xiàn)在所有的代碼都編寫好了,看下最后的效果
 
這樣簡(jiǎn)單的效果就出來(lái)了。

標(biāo)簽:廣元 江蘇 衢州 棗莊 蚌埠 大理 衡水 萍鄉(xiāng)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用$.get()根據(jù)選項(xiàng)的不同從數(shù)據(jù)庫(kù)異步請(qǐng)求數(shù)據(jù)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266