您的位置:首页 > Web前端 > JavaScript

Ajax与JSON技术

2015-07-28 17:00 627 查看
Ajax实现简单的验证:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function ajaxValid(){
var xhr=null;
var username=document.getElementById("username").value;
//创建XMLHttpRequst对象,今后主要靠此对象进行与后台交互
if(window.ActiveXObject){
//IE5,6创建对象的方式
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}else{
xhr=new XMLHttpRequest();
}
//打开连接
xhr.open("get", '/Web030Ajax/AjaxServlet?username='+username);
//发送请求
xhr.send(null);
xhr.onreadystatechange=function(){
//readyState码,0代表未初始化,1正在加载2已加载3正在交互4完成
if(xhr.readyState==4){
//服务器响应码,200成功
if(xhr.status==200){
//	console.log('成功');
var jsondata=JSON.parse(xhr.responseText);
//alert(jsondata.info);
document.getElementById("info").innerHTML=jsondata.info;
}
}
};
}

</script>
</head>
<body>
<form action="">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="username" id="username" onblur="ajaxValid()"/><span id="info"></span></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password" id="password"/></td>
</tr>

</table>

</form>
</body>
</html>
servlet端
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username=request.getParameter("username");
PrintWriter out=response.getWriter();
if(username.equals("admin")){

out.print("{\"info\":\"exit\"}");
}else{

out.print("{'info':'ok'}");
}
}
省份
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

function ff(){
var selected=document.getElementById("selected1");
selected.onclick=function (){
var xhr=null;
xhr=new XMLHttpRequest();

xhr.open("post","/Web030Ajax/Province");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//注意这句话的顺序
xhr.send(null);
xhr.onreadystatechange=function (){
if(xhr.readyState==4){
var prostr=xhr.responseText;
var arry=JSON.parse(prostr);
document.getElementById("selected").innerHTML='';
for(var i=0;i<arry.length;i++){
document.getElementById("selected").innerHTML+='<option>'+arry[i]+'</option>';
}
}

};

}
}

</script>
</head>
<body onload="ff()">
<form action="" >
<select id="selected">

</select>
<input type="button" value="dianwo" id="selected1">
</form>

</body>
</html>
servlet端
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
PrintWriter out=response.getWriter();
List<String> provinces=new ArrayList<String>();
provinces.add("山东");
provinces.add("北京");
provinces.add("上海");
String jsondata=JSONArray.fromObject(provinces).toString();
out.print(jsondata);
out.close();
}


本文出自 “Java大白的战地” 博客,请务必保留此出处http://8023java.blog.51cto.com/10117207/1679280
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: