Ajax实现

前端之家收集整理的这篇文章主要介绍了Ajax实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文是为了验证创建用户时通过ajax异步的检测数据库中该用户是否存在。

editUser.jsp核心代码

<input class="input1" type="text" name="username" id="username" value="${createUser.username}" onblur="checkName();"/>*

editUser.js中的核心代码

function checkName(){


document.getElementById("username2").innerHTML ="";


var name=document.getElementById("username").value;


if(!name){


document.getElementById("username2").innerHTML ="Please input the username";


return;


}


var regex=/^[a-zA-Z0-9_\u4e00-\u9fa5]{3,15}$/;


if(!name.match(regex)){


document.getElementById("username2").innerHTML ="The formate of the username is not right";


return;


}


$.ajax({


type:"POST",


url:contextURL+"/user/getUser",


data:{username:name},


success:function(msg)


{ if(msg==1){


document.getElementById("username2").innerHTML ="The user exist";


}


},


error:function()


{


alert("the connection Failed");


}


});


}


UserController中的核心代码

/**



* Judge the user isExist by ajax


*/


@RequestMapping(value = { "/getUser" },method = { RequestMethod.POST })


@ResponseBody


public int getUser(@RequestParam(value = "username") String username) {


try {


User user = userService.getUserByName(username);


if (user != null) {


return Constants.IS_EXIST;


}


} catch (ParameterException e) {


e.printStackTrace();


logger.error(e.getMessage(),e);


throw new RuntimeException(e);


}


return Constants.NO_EXIST;


}

这样就是实现了异步用户检测功能



猜你在找的Ajax相关文章