JQuery的Ajax实现注册检测用户名

Ajax(无需等待直接向服务器发起请求)

(Asynchronous

Javascript

And

Xml) :异步的

Google创新的一种js技术

 

实现方法一:比较原始没有封装的方法:

 1  //核对用户名是否可用
 2         var xmlhttp = null;
 3 
 4         function checkUser(userName) {
 5             if (xmlhttp == null) {
 6                 xmlhttp = new XMLHttpRequest();//第一步:创建一步通信对象
 7             }
 8             //第二步:设定回调函数
 9             xmlhttp.onreadystatechange = function () {
10                 if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
11                     $("#tip").html(xmlhttp.responseText);
12                 }
13             }
14             xmlhttp.open("get", "register?op=check&userName=" + userName);
15             xmlhttp.send();
16         }

从文本框中输入一个字符后就立即到数据库中查找该用户名是否存在,如果存在,提示不可用,直到可用为止;

方法二:JQuery的Ajax:

 1    //核对用户名是否可用
 2         function checkUser(userName) {
 3             $.ajax({
 4                 type: 'post',//如果是get可以不写type,默认是get
 5                 url: "register",//action方式
 6                 data: {op: 'check', userName: userName}, //参数,如果参数多,可用date后跟一个大括号
 7                 success: function (res) {//回调函数
 8                     if (res.indexOf("yes") !== -1) {
 9                         $("#tip").html("Yes! Available: user name!");//可用
10                         //$("#tj").prop("disabled", false); //设置按钮可用
11 
12                     } else {
13                         $("#tip").html("No! User name: not available!");//不可用
14                         // $("#tj").prop("disabled", true); //设置按钮不可用
15                     }
16 
17                 }
18             });
19         }

运行效果和上面一样; 

原文地址:https://www.cnblogs.com/lwl80/p/13516951.html