---
title: "ajax的helloworld(2)"
author: "itgo"
date: "2014-06-17T16:43:41Z"
tags: []
categories: ["编程语言"]
slug: "ajax-helloworld-2"
draft: false
lastmod: "2014-06-17T16:43:41Z"
id: 2081832
url: "https://itgo.iteye.com/blog/2081832"
---

本文在《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对象。