栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript > Ajax教程

使用$.get()根据选项的不同从数据库异步请求数据

Ajax教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用$.get()根据选项的不同从数据库异步请求数据

Ajax极大地改善了用户体验,对于web2.0来说必不可少,是前端开发人员必不可少的技能。

这个例子是这样的,当从select下拉框选择编程语言时时,根据选项的不同,异步请求不同的函数API描述。这种功能在现在web应用程序中是及其常见的。

我们先来看一下$.get()的结构
复制代码 代码如下:
$.get(url, [, data], [, callback] [, type])
//url:请求的HTML页的URL地址;
//data(可选),发送至服务器的key/value数据作为QueryString附加到请求URL中;
//callback(可选):载入成功时的回调函数(只有当Response的返回状态是success才调用该方法;
//type(可选):服务器端返回内容格式,包括xml,html,script,json,text和_default

首先创建examplDB数据库,建立language和functions表,SQL如下
复制代码 代码如下:
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));

下面是插入数据的SQL
复制代码 代码如下:
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'');rnprint_r($xml);rn'),
(2, 1, 'array_push', 'Push one or more elements onto the end of array', '$arrPets = array(''Dog'', ''Cat'', ''Fish'' );rnarray_push($arrPets, ''Bird'', ''Rat'');rn'),
(3, 1, 'ucfirst', 'Make a string''s first 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(mail(''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,rn success: success,rn dataType: dataTypern});rn'),
(6, 2, 'hover', 'hover method accepts 2 functions as parameters which execute alternativelt when mouse enters and leaves an 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 associated with the specified element.', 'jQuery.data(element, key, value);'),
(9, 1, 'add class', 'Adds a class', '(''p'').addClass(''myClass yourClass'');');

都是比较简单的SQL操作,一切准备就绪后就可以编码了。总共有两个脚本文件,一个index.php,一个results.php用于处理请求,先编写index.php
复制代码 代码如下:





body {font-family:"Trebuchet MS", Verdana, Arial; width:600px;}
div {background-color:#f5f5dc;}




$mysqli = new mysqli('localhost', 'root', 'passwd', 'exampledb');//将passwd改为你的数据库密码
if (mysqli_connect_errno())
{
die('Unable to connect');
}
else
{
$query = 'SELECT * FROM language'; //这里开始是核心代码,都是很简单的语句,主要是在language中取得记录,然后循环输出到select选项
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>


Select a languae



}
else
{
echo 'No records found';
}
$result->close();
}
else
{
echo 'Error in query: $query.'.$mysqli->error;
}
}
$mysqli->close();
?>





引入jquery,给#selectLanguage添加change事件处理程序,并放在index.php中body结束前
复制代码 代码如下:



下面就是results.php了。它先连接到数据库,然后取得index.php发送到id,根据id在数据库里选择相应的编程语言记录,并将每条记录放到ul列表中
复制代码 代码如下:
$mysqli = new mysqli('localhost', 'root', 'passwd', 'exampledb'); //这里也要用你的数据库密码改写passwd
$resultStr = '';
$query = 'SELECT functionName, summary, example FROM functions where languageId ='.$_GET['id']; //$_GET['id']就是index.php中用$.get()发送的id
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
$resultStr .= '
    ';
    while($row = $result->fetch_assoc()) //和index.php的语句差不多,也是先从数据库取得记录,然后格式化输出
    {
    $resultStr .= '
  • '.$row['functionName'].'-'.$row['summary'];
    $resultStr .= '
    '.$row['example'].'
    '.'
  • ';
    }
    $resultStr .= '
';
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>

现在所有的代码都编写好了,看下最后的效果
 
这样简单的效果就出来了。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/128714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号