struts2.1实现ajax通信

首先去下载 http://code.google.com/p/jsonplugin/downloads/list 先

还有记得加埋strtus官方lib里面有关json的jar包

然后添加测试action

package com.json;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class JSONExample extends ActionSupport implements  ServletRequestAware{

	private static final long serialVersionUID = 8465922425903754099L;
	private String tip;
	private Map map = new HashMap();
	private HttpServletRequest request;

	@JSON(name="testMap")
	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	@JSON(name="newName")
	public String getTip() {
		return tip;
	}

	public void setTip(String tip) {
		this.tip = tip;
	}

	
	@Override
	public String execute() throws Exception {
		setTip( "系统中已有用户名,请重新选择一个!");
		this.map.put("ok", "dd");
		this.map.put("ss", "lal");
		System.out.println("************"+this.request.getParameter("name"));
		return SUCCESS;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
	}


}

 页面使用jqurey

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
	$(document).ready( function() {
		$("a").click( function() {
			$.getJSON("JSONExample.action","name="+$("#asdf").value, function(json){
			  $("#ss").html(json.testMap.ss);
			  $("#ok").html(json.testMap.ok);
			  $("#newName").html(json.newName);
			}); 
		});
	});
</script>
<a href="#">dfdf</a>
<div id ="ss"></div><br>
<div id="newName"></div><br>
<div id ="ok"></div>

 struts.xml中加入

<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="com.json" extends="json-default">
		<action name="JSONExample" class="com.json.JSONExample">
			<result type="json" />
		</action>
	</package>

 然后试试

你可能感兴趣的:(JavaScript,jquery,json,Ajax,struts)