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


<script src="https://www.jb51.net/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了。它先连接到数据库,然后取得index.php发送到id,根据id在数据库里选择相应的编程语言记录,并将每条记录放到ul列表中

复制代码 代码如下:


<?php
$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 .= '<ul>';
while($row = $result->fetch_assoc()) //和index.php的语句差不多,也是先从数据库取得记录,然后格式化输出
{
$resultStr .= '<li><strong>'.$row['functionName'].'</strong>-'.$row['summary'];
$resultStr .= '<div><pre>'.$row['example'].'</pre></div>'.'</li>';
}
$resultStr .= '</ul>';
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>


现在所有的代码都编写好了,看下最后的效果

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

 
这样简单的效果就出来了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfwypj.html