ajax 异步处理 使用js、jQuery分别实现Get请求 Post请求
0102、Get方法 js的编写
var xmlHttpRequest = null; //1、创建XMLHttpRequest对象 if (window.XMLHttpRequest) {//新版本返回为TRUE xmlHttpRequest = new XMLHttpRequest(); } else { xmlHttpRequest = new ActiveXObject( "Microsoft.XMLHTTF"); } //2、设置回调函数 xmlHttpRequest.onreadystatechange = callBack; var username = $("#username").val(); //3、初始化XMLHttpRequest组件 var url = "UserServlet?username=" + username; xmlHttpRequest.open("GET", url, true); //4、发送请求 xmlHttpRequest.send(null); //回调函数callBack的编写 function callBack() { if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { var data = xmlHttpRequest.responseText; if (data == "true") { $("#errMsg").html("用户名已被注册"); } else { $("#errMsg").html("用户可以注册"); } } } });
0102、Post方法 js的编写
$("#username").blur( function() { //1、创建XMLHttpRequest对象 var xmlHttpRequest = null; if (window.XMLHttpRequest) {//新版本返回为TRUE xmlHttpRequest = new XMLHttpRequest(); } else { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTF"); } //2、设置回调函数 xmlHttpRequest.onreadystatechange = callBack; //3、初始化XMLHttpRequest组件 var url = "UserServlet"; xmlHttpRequest.open("POST", url, true); xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //4、发送请求 var username = $("#username").val(); var data = "username=" + username; xmlHttpRequest.send(data); //回调函数callBack的编写 function callBack() { if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { var data = xmlHttpRequest.responseText; if (data == "true") { $("#errMsg").html("该用户已被注册"); } else { $("#errMsg").html("用户名可以使用"); } } } })
0103、$.ajax Get的编写
$("#username").blur(function() { var username = $(this).val(); $.ajax({ "url" : "UserServlet", //提交URL "type" : "Get",//处理方式 "data" : "username=" + username,//提交的数据 "dataType" : "text",//指定返回的数据格式 "success" : callback,//执行成功后的回调函数 "async" : "false",//是否同步 //错误后执行 "error" : function() { alert("验证出现错误!") } }); function callback(data) { alert(data); if (data == "true") { $("#errMsg").html("用户名已被注册!"); } else { $("#errMsg").html("用户名可以使用!"); } } })
0104、$.get(url,[data],[success])的代码
$("#name").blur(function() { var name = $(this).val(); if (name != null && name != "") { $.get("UserServlet","name="+name,callBack); function callBack(data) { if (data == "true") { $("#msg").html("用户名已存在"); } else { $("#msg").html("用户名可以使用"); } } } });
0105、$.post(url,[data],[success])的代码
$("#name").blur(function() { var name = $(this).val(); if (name != null && name != "") { $.post("UserServlet", "name=" + name, callBack); function callBack(data) { if (data == "true") { $("#msg").html("用户名已存在!"); } else { $("#msg").html("用户名可以使用!"); } } } });