Ajax练习题
Posted 雍家培
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax练习题相关的知识,希望对你有一定的参考价值。
1、使用Ajax跳转处理页面连接数据库,完成下拉列表
首页:
<body>
<select id="sel"> </select>
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$.ajax({
url:"chuli.php", //处理页面
data:{}, //要提交的值
type:"POST", //提交方式
dataType:"TEXT", //返回类型
success:function(s){ //回调函数
var hang = s.split("|");
var str = "";
for(var i=0;i<hang.length;i++) {
var lie = hang[i].split("^");
str = str+"<option value=‘"+lie[0]+"‘>"+lie[1]+"</option>";
}
$("#sel").html(str);
}
});
});
</script>
处理页:
<?php
include("../DBDA.php");
$db = new DBDA();
$sql = "select * from Nation";
$attr = $db->Query($sql);
$str = "";
foreach($attr as $v){
$str = $str.implode("^",$v);
$str = $str."|";
}
$str = substr($str,0,strlen($str)-1);
echo $str; //通过字符串操作返回字符串
2、测试用户名是否可用
首页:
<body>
<div>用户名:<input type="text" id="uid" /><span id="xx"></span></div>
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$("#uid").blur(function(){
var uid = $(this).val();
//调AJAX
$.ajax({
url:"uidchuli.php",
data:{u:uid},
type:"POST",
dataType:"TEXT",
success: function(data){
if(data.trim() == "OK"){ //去空格
var str = "该用户名可以使用";
$("#xx").html(str);
$("#xx").css("color","green");
} else {
var str = "该用户名已存在!";
$("#xx").html(str);
$("#xx").css("color","red");
}
}
});
})
});
</script>
处理页:
<?php
$uid = $_POST["u"];
include("../DBDA.php");
$db = new DBDA();
$sql = "select count(*) from Users where Uid=‘{$uid}‘";
$attr = $db->Query($sql);
if($attr[0][0]>0){
echo "NO";
}else{
echo "OK";
}
3、返回值为Json的操作
首页:
<body>
<br />
<div>请输入代号:<input type="text" id="code" />
<input type="button" value="查询" id="btn" />
</div>
<br />
<div id="name"></div>
<br />
<br />
<div>请选择:<select id="sel">
<option value="p001">张三</option>
<option value="p002">李四</option>
<option value="p003">王五</option>
</select></div>
<br />
<div id="xinxi"></div>
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$("#btn").click(function(){
var code = $("#code").val();
$.ajax({
url:"selchuli.php",
data:{code:code},
type:"POST",
dataType:"JSON",
success: function(data){
$("#name").text(data.name);
}
});
})
$("#sel").change(function(){
var code = $(this).val();
$.ajax({
url:"xxchuli.php",
data:{code:code},
type:"POST",
dataType:"JSON",
success: function(data){
var str = "<span>代号:"+data[0]+"姓名:"+data[1]+"性别:"+data[2]+"生日:"+data[4]+"</span>";
$("#xinxi").html(str);
}
});
})
});
</script>
selchuli.php处理页:
<?php
$code = $_POST["code"];
include("../DBDA.php");
$db = new DBDA();
$sql = "select Name from Info where Code = ‘{$code}‘";
$attr = $db->Query($sql);
//做一个关联数组
$arr = array();
$arr["name"] = $attr[0][0];
//将数组转换为JSON
echo json_encode($arr);
xxchuli.php处理页:
<?php
$code = $_POST["code"];
include("../DBDA.php");
$db = new DBDA();
$sql = "select * from Info where Code = ‘{$code}‘";
$attr = $db->Query($sql);
echo json_encode($attr[0]); //如果是二维数组,在主页面可以使用for(var at in data)循环
以上是关于Ajax练习题的主要内容,如果未能解决你的问题,请参考以下文章