首先在用ajax之前,先说一下JSON:
JSON:javascript object notation js对象标记
对于json,我们只需要知道如何定义json?如何输出?怎么遍历?
1、定义json
var a =
{
"one":"111",
"two":"222",
"three":arr, -------可以是数组(var arr=new Array(2,3,4))
"four":{"hello":"您好"}------可以是json
}
由此可知:我们用花括号保存对象,用逗号分隔,写法有点像关联数组
2、输出json
alert(a.one)
alert(a.four.hello)
3、遍历json
for(var k in a)
{
alert(a[k]);
}
例题1:判断用户是否存在?
1.这里需要跟数据库进行连接判断
这是我用的表
2.实现的效果
这是还没被注册的
这是注册的
代码如下:
1 <title>无标题文档</title> 2 <script src="jquery-3.2.0.js"></script>//引用jquery包 3 </head> 4 5 <body> 6 <input type="text" id="uid" /><span id="tishi"></span> 7 </body> 8 <script type="text/javascript"> 9 $("#uid").blur(function(){ 10 //取数据 11 var uid = $(this).val(); 12 13 //取数据库进行匹配 14 $.ajax({ 15 url:"tianjia.php", 16 data:{u:uid}, 17 type:"POST", 18 dataType:"TEXT", 19 success: function(data){ 20 if(data.trim()=="OK") 21 { 22 $("#tishi").html("该用户名可用"); 23 $("#tishi").css("color","green"); 24 } 25 else 26 { 27 $("#tishi").html("该用户名不可用"); 28 $("#tishi").css("color","red"); 29 } 30 } 31 32 33 34 35 36 }) 37 38 39 40 }) 41 42 </script>
处理页面代码:
1 <?php 2 $uid=$_POST["u"]; 3 require "DBDA.class.php"; 4 $db=new DBDA(); 5 6 $sql="select count(*) from yuangong where UserName='{$uid}'"; 7 $arr=$db->query($sql); 8 if($arr[0][0]) 9 { 10 echo "NO"; 11 } 12 else 13 { 14 echo "OK"; 15 }
例题2,往数据库中添加数据
数据库
然后我们再看数据库就有了
页面代码:
1 <title>无标题文档</title> 2 <script src="jquery-3.2.0.js"></script> 3 </head> 4 5 <body> 6 <h1>添加数据</h1> 7 <div>代号:<input type="text" id="biaohao" /></div> 8 <div>民族:<input type="text" id="minzu" /></div> 9 <input type="button" value="添加" id="add" /> 10 </body> 11 <script type="text/javascript"> 12 $("#add").click(function(){ 13 var biaohao=$("#biaohao").val();//取值 14 var minzu=$("#minzu").val(); 15 16 $.ajax({ 17 url:"tianjia.php", 18 data:{b:biaohao,m:minzu}, 19 type:"POST", 20 dataType:"TEXT", 21 success: function(data){ 22 if(data.trim()=="OK") 23 { 24 alert("添加成功"); 25 } 26 else 27 { 28 alert("添加失败"); 29 } 30 31 } 32 33 34 }); 35 }) 36 37 38 </script>
处理页面
1 <?php 2 $biaohao=$_POST["b"]; 3 $minzu=$_POST["m"]; 4 require "DBDA.class.php"; 5 $db=new DBDA(); 6 7 8 $sql="insert into nation values('{$biaohao}','{$minzu}')"; 9 if($db->query($sql,0)) 10 { 11 echo "OK"; 12 } 13 else 14 { 15 echo "NO"; 16 }