Ajax+PHP检查用户名或邮件(三)

原理:

1、输入用户名

2、触发控件

3、获得填写内容

4、Ajax传递

5、查询数据库

6、返回结果

7、DOM反应到页面

页面触发的几种类型

onblur 事件会在对象失去焦点时发生。

onchange 事件会在域的内容改变时发生。

onclick 事件会在对象被点击时发生。

onfocus 事件在对象获得焦点时发生。

onkeydown 事件会在用户按下一个键盘按键时发生。

onkeypress 事件会在键盘按键被按下并释放一个键时发生。

onkeyup 事件会在键盘按键被松开时发生。

onmousedown 事件会在鼠标按键被按下时发生。

onmousemove 事件会在鼠标指针移动时发生。

onmouseout 事件会在鼠标指针移出指定的对象时发生。

onmouseup 事件会在鼠标按键被松开时发生。

获取表单中的数据内容

<form name="myform" …

<input name=user type=textvalue="">

</form>


js:

document.myform.user.value

实现代码:

index.php

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="ajax.js"></script>
<form name="myform" action="" method="post" enctype="text/plain">
用户名:
<input type="text" name="user" value="" onblur="funphp100('php100')"/>
<div id="php100"></div>
</form>

分析:通过onbluur触发js中的函数funphp100();

ajax.js

var xmlHttp;
function S_xmlhttprequest() {
	if(window.ActiveXObject) {
		xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
	} else if(window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

function funphp100(name) {

        var f=document.myform.user.value;
        f=encodeURI(f);//解决汉字不能正确传递的问题
        S_xmlhttprequest();
	xmlHttp.open("GET","for.php?id="+f,true);
	xmlHttp.onreadystatechange = byphp;
	xmlHttp.send(null);
}

function byphp() {

  	if(xmlHttp.readyState == 1) {
		 document.getElementById('php100').innerHTML = "<img src='loading.gif'>";
	}

    	if(xmlHttp.readyState == 4 ){
		if(xmlHttp.status == 200) {
          var byphp100 =  xmlHttp.responseText;
          document.getElementById('php100').innerHTML = byphp100;
		}
	}


}

分析:

xmlHttp.open("GET","for.php?id="+f,true);

f(即myform表单中user输入框中的值)需要通过get方式通过URL传递到for.php中进行操作,但是汉字直接通过这个方式进行传递会出现乱码,所以需要先通过encodeURL(f)函数,进行转换。

for.php

<?php
header("charset=utf-8");
$url=@$_GET[id];
if($url){
          sleep(1);
          $conn=mysql_connect('localhost','root','');
          mysql_select_db('test',$conn);
          mysql_query("set names utf8");
          echo $sql="SELECT * FROM `user` where `user`='$url'";
          $q=mysql_query($sql);
          if(is_array(mysql_fetch_row($q))){
	             echo "<font color=red>用户名已经存在</font>";
                 }else {
                     echo "<font color=green>可以使用</font>";
                  }
       }
?>


posted @ 2013-06-12 23:21  千手宇智波  阅读(187)  评论(0编辑  收藏  举报