`
itgo
  • 浏览: 2723 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

ajax的helloworld(2)

    博客分类:
  • ajax
阅读更多

本文在《ajax的helloworld(1)》进行修改。使用json返回数据。

第一步:

创建User类:

 

package com.entity;

public class User {
	private int userId;
	private String userName;
	private String password;
	public User(){
		
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	
}

 第二步:

 

修改RegisterSer:

 

public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		User user = new User();
		user.setUserName("I am userName");
		JSONArray json = JSONArray.fromObject(user);
		response.getWriter().write(json.toString());
	}

 (PS..加上response.setContentType("text/html;charset=UTF-8");解决中文乱码问题

本文使用json-lib.jar来拼接json字符串。也可以自己手动写json字符串。)

第三步:

修改js:

$(document).ready(function() {
	$("#userName").change(function(){
		$.ajax({
			 url:'RegisterSer',
			 data:{userName:$("#userName").val()},
			 type: "POST",
			 datatype: "json",
			 error:function(){
	             alert("error occured!!!");
	         },
	         success:function(data){
	        	 var userJson = eval(data);
	        	 alert(userJson[0].userName);
	         }
		})
	});
});

 加上datatype: "json",表示返回数据类型为json。

使用eval()方法将json字符串转为json对象。

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics