`

Struts2 + jQuery 实现ajax (二) 回调函数

阅读更多

情景描述:

     利用Struts2 + jQuery 实现ajax时候,如何获取返回值的信息来正确的提示用户。例如给某个电影打分rating,每个用户只能对一个电影打一次分数,如果打第二次的时候就提示用户"已经打过分了"。

1.js代码:
function ratingMovieClick(userId,num,movieId){
	if (userId == 0) {
		alert("You have to be logged in to rating !")
		return;
	}else{
		var url = "../RatingMovie.action";
		var params = {
			userId : userId,
			num : num,
			movieId : movieId
		};
		jQuery.post(url, params, callbackFun, 'json');
	}
}

function callbackFun(data) {
	alert(data);
}

 

2.配置文件:注意这里的<param name="root">result</param>这句将请求处理返回的结果带回到页面中。
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="Struts2_AJAX" extends="json-default">		
		<action name="RatingMovie" class="com.action.RatingAction" method="addRatingMovie">
			<result type="json">
				<param name="root">result</param>
			</result>
		</action>
	</package>
</struts>

 

 

3.java代码:这里定义的result就是在配置文件里面定义的,这2个要一致。
public class RatingAction extends AbstractAction{
	
	private double avg_rating ;
	private int count;
	private String result;
	
	private static String CALL_BACK_1 = "You have ratinged !";
	private static String CALL_BACK_2 = "Thanks for rating !";
	
	private IRatingService ratingService;
	private IMovieService movieService;
	
	/**
	 * check the records.
	 * @param obj1
	 * @param obj2
	 * @return
	 */
	public int checkRelatedTableRecord(long obj1, long obj2){
		if(ratingService == null){
			count = getRatingService().getRecordRating(obj1, obj2);
		}else{
			count = ratingService.getRecordRating(obj1, obj2);
		}
		return count;
	}
	
	public String addRatingMovie(){
		int record = this.checkRelatedTableRecord(userId, movieId);
		if(record > 0){
			this.result = CALL_BACK_1;
			return "success";
		}else{			
			Related related = new Related();
			related.setType(Related.TYPE_RATING_MOVIE);
			related.setObj1(userId);
			related.setObj2(movieId);
			related.setDegree(num);
			related.setCreated(new Date());
			related.setModified(new Date());
			ratingService.addRating(related);
			avg_rating = ratingService.getAvgRating(Related.TYPE_RATING_MOVIE, movieId);
			Movie movie = movieService.getMovieById(movieId);
			movie.setRating(new Float(avg_rating));
			movieService.updateMovie(movie);
			this.result = CALL_BACK_2;
			return "success";
		}
	}
		
	public void setRatingService(IRatingService ratingService) {
		this.ratingService = ratingService;
	}

	public void setMovieService(IMovieService movieService) {
		this.movieService = movieService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}	
}

 

    这样当record > 0时,数据库里面已经有记录的时候,就this.result = CALL_BACK_1;return "success"; 这里的result就会赋值成"You have ratinged !",这样在回调函数中就可以拿到这个字符串了。这里的返回值只能是"success",我试过好几个都会报错!

 

下面是某个参考某论坛上的信息:http://www.iteye.com/topic/560638

 一、准备一个JSP页面用于提交ajax请求,这里我使用了JQuery的$.getJSON(url,params,function callback(data))函数提交ajax请求到指定url,并且携带参数params,最后用一个回调函数callback处理请求返回结果data;

二、一个处理请求的Action类,并在struts.xml文件中做相应配置:写一个action类处理ajax请求数据,并将返回结果封装成一个JSONObject对象返回给请求页面。同时在struts.xml中配置对应action,指明其返回类型为json并使其package的extends为json-default,并将要返回请求页面的数据放在名为root的param中,如<param name="root">result</param>。

三、接受请求返回结果:使用JS的eval方法将返回结果data转换成JSON对象,并处理返回结果。

$.getJSON(url,params,function callback(data){   
        // convert to json object   
        var user = eval("("+data+")");//   
           
           
        $("#result").each(function(){   
            $(this).html('welcome ,' + user.name);   
            });   
        });   
    }   
public String login() throws Exception {   
           
        Map map = new HashMap();   
        map.put("name", user.getLogName());   
        map.put("password",user.getPassword());   
        JSONObject obj = JSONObject.fromObject(map);   
           
           
        result = obj.toString();   
           
        return SUCCESS;   
    }  

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics