1.首先先見一個小web項目
先建一個User類:
package com.json;
public class User {
String username;
String password;
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;
}
}
再建一個servlet
package com.json;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
public class TestJson extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String str= request.getParameter("name");//獲得ajax傳遞過來的paramater
System.out.print(str);
PrintWriter out = response.getWriter();
List list = new ArrayList();//傳遞List
Map m=new HashMap();//傳遞Map
User u1=new User();
u1.setUsername("zah");
u1.setPassword("123");
User u2=new User();
u2.setUsername("ztf");
u2.setPassword("456");
list.add(u1); //添加User對象
list.add(u2); //添加User對象
m.put("u1", u1);
m.put("u2", u2);
JSONArray jsonArray2 = JSONArray.fromObject( list );//轉化成json對象
JSONObject jo=JSONObject.fromObject(m);//轉化Map對象
out.print(jsonArray2);//返給ajax請求
out.print(jo);//返給ajax請求
}
}
配置好web.xml中的servlet映射,這一步就略了。
2.創建ajax實現
這裏爲了快速實現用的是jquery實現的。
<script type="text/javascript" src="js/jquery.js"></script>
< script type="text/javascript">
function test(){
$.ajax({
type:"POST", //請求方式
url:"testjson", //請求路徑
cache: false,
data:"name=zah", //傳參
dataType: 'json', //返回值類型
success:function(json){
alert(json[0].username+" "+ json[0].password); //彈出返回過來的List對象
}
});
}
< /script>
</head>
<body>
<input type="button" name="b" value="測試" onclick=test()>
</body>
3測試開始,點擊按鈕彈出zah 123
json[0]就至關於u1對象 json[1]至關於u2對象,對於其屬性的訪問跟java對象同樣,其餘的Connection測試應該同樣,javascript
訪問Map的話直接把返回函數改爲以下便可:
success:function(json){
alert(json.u1.username)
}
}直接跟上Key.屬性便可訪問Object對象。
html