用jquery使用ajax例子

来源:互联网 发布:java中变量的定义方法 编辑:程序博客网 时间:2024/05/01 10:33
数据库test    表ta
表内容:
+----+------+
| id | name |
+----+------+
|  1 | aa   |
|  2 | bb   |
+----+------+
***************************************************************************
展示文件test.php
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>jquery_ajax</title>
<script language="javascript" src="jquery.js"></script>
<style type="text/css">
#msg{
  background:yellow;
  width:500px;
  height:300px;
  display:block;
}
</style>
<script language="javascript">
$(document).ready(function(){
$("#user").keyup(function(){
  var username = $(this).val();
  var url = "ajax.php";
  if(username != ""){
   $.get(url,
     {name:username},
     function(data){
    if(data == 0){
     $("#msg").html("可以注册!");
    }
    else{
     $("#msg").html("用户名已经使用!");
    }
     }
   );
  }
  else{
   $("#msg").html("用户名为空!");
  }
  });
})
</script>
</head>
<body>
<input type="text" id="user" name="user" />

<span id="msg"></span>
</body>
</html>
+----------------------------------------------------+
ajax调用文件:
ajax.php
<?php
/**
*查询用户名
*
*/
mysql_connect("localhost","usr","pwd");
mysql_select_db("test");
$str = "select count(name) from ta where name='{$_GET['name']}';";
$query = mysql_query($str)or die("aaaaaaa");
while($row = mysql_fetch_row($query)){
echo $row[0];
}
?>

*******************************
ajax的另一种写法
<script language="javascript">
$(document).ready(function(){
$("#user").keyup(function(){
  if(event.keyCode == 13){
   return false;
  };
  var username = $("#user").val();
  var url = "ajax.php";
  $.ajax({
   type:"GET",
   url:"ajax.php",
   data:"name="+username,
   success:function(msg){
    if(msg == 0){
     $("#msg").html("用户名可以使用!");
    }
    else{
     $("#msg").html("<font color='red'>用户名已经被使用!</font>");
    }
   }
  });
});
})
</script>

 

原创粉丝点击