我用MyEclips教程e工具內建的功能匯入jar的時候,預設這個jsonplugin就已經被匯入了,所以只需要在Myeclipse看看,是不是已經匯入了這個包,如果已經有了,那麼就不用匯入了。
好,回到正題。上次說到這是擷取一個值,那麼如果是一個對象呢?一個集合呢?
public class Book
{
private String bookName;
private String author;
//此處省略這兩個成員變數的getter 和setter
public Book(){}
public Book(String bookName,String author)
{
this.bookName=bookName;
this.author=author;
}
}
Action內容
public class TestAction extends ActionSupport
{
private Book book;
private List<Book> bookList;
public String execute()
{
bookList=new ArrayList<Book>();
book=new Book();
book.setBookName("三十天");
book.setAuthor("Blak");
list.add(new Book("世界第一等","是是"));
list.add(new Book("一直很安靜","阿桑"));
list.add(new Book("Struts 2","me"));
}
}
struts.xml
<package name="ajax" extends="json-default">
<action name="testjson" class="action.TestJsonAction">
<result type="json">result</result>
</action>
</package>
頁面內容
<html>
<head>
<title>testJson</title>
<script type="texxt/網頁特效" src="js/jquery.js"></script>
<script type="texxt/javascript" >
function testJson()
{
$.ajax({
type:"post",
url:"testjson.action",
data:{},
dataType:"json",
beforeSend:function(){},
success:function(json){
alert("success complete");
alert("bookName:"+json.book.bookName+" Author:"+json.book.author);
var json=eval(json.bookList);
json = eval(json.list)
for(var i=0; i<json.length; i++)
{
alert(json[i].bookName+" " + json[i].author)
}
}
});
}
</script>
</head>
<body>
This is my page!<br />
<hr />
<input type="button" value="測試Ajax" onclick="testJson();" />
</body>
</html>
訪問一個對象的 話,直接用json.對象名.欄位名 就可以了