ajax同步:req.open(‘get’,url,false);
实例:
js方法
var g_success =false;//全局变量
function getUser(username){
if("" == username){
alert("登录名不能为空!");
return;
}
g_success = false;
var url = "<%=path%>/basicdata/gyshtyCheckUsername.do?mode=getUser&username="+encodeURI(encodeURI(username));
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} elseif (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req) {
req.open('get',url,false);//同步
req.setRequestHeader("Content-Length",username.length);
req.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
req.send("username="+encodeURI(encodeURI(username)));
if (req.readyState == 4){
if (req.status == 200){
result = req.responseText;
if('no.' == result){
alert("登录名不存在!");
document.getElementById("username").value ="";
document.forms[0].username.focus();
}else{
g_success = true;
}
}
}
}
}
二、后台服务类
String username = request.getParameter("username");
Users users = gyshtyService.findUsersByUsername(username);
String jsonStr="no";
if (users!=null) {
jsonStr = users.getUsername();
}else{
jsonStr = "no.";
}
response.setContentType("text/xml;charset=GBK");
response.setHeader("Cache-control","no-cache");
response.getWriter().print(jsonStr);
returnnull;
ajax异步:req.open(‘get’,url,true);
实例:
一、js方法
function getNext(){
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} elseif(window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req) {
var url = “------”;
req.open("GET",url,true);
req.onreadystatechange = completeGetNext; //回调函数
req.send(null);
}
}
function completeGetNext(){
if(req.readyState == 1) {
document.getElementById("loadspan").innerHTML =
"<img src='../image/loading.gif' align='absmiddle'> <font color=red>数据加载中,请等待...</font>";
}
if(req.readyState == 4) {
if(req.status == 200) {
//取到结果之后,开始......
parseMessageNext();
}
}
}
二、后台服务类
response.setContentType("text/xml;charset=GBK");
response.setHeader("Cache-control","no-cache");
String xml = "<?xml version=\"1.0\" encoding=\"GBK\" ?>";
/*
与数据库交互,业务逻辑等
*/
response.getWriter().write(xml + str);
个人总结:在使用异步(true)时可以定义回调函数,在使用同步(false)时回调函数不能另定义一个回调函数名字。个人不知道原因所在,希望大家告诉一下原因。
备注:以上代码是开发中已经实现功能的代码。