日期:2014-05-16  浏览次数:20393 次

ajax+json应用实例

准备工作:

?? a: 导入包:struts2-json-plugin-2.2.1.jar

注意事项:

?? a:为了保能能获取json的返回值,需要将action中使用的所有的service接口的所有get方法上添加@JSON(serialize=false)标记

-----------------------------------------

1. js 前台

?

// 完成新增试卷模板
?????????? function??? addPaperTemplateSubmit(){
??????????
??? ?????????? // 获取试卷模板名称和总分
??? ?????????? var templateName = $.trim($("#templateName").val());
??? ?????????? var totalMark = $.trim($("#totalMark").val());
????????????? alert("totalMark="+totalMark+"===templateName="+templateName);
??????????
??? ?????????? $.ajax({
??? ??? ??? ??? type : "get",
??? ??? ??? ??? async: false,????? //ajax同步
??? ??? ??? ??? url : "<%=path%>/admin/questionbank_ajax/checkPaperTemplate.action",
??? ??? ??? ??? data: "templateName="+encodeURIComponent(encodeURIComponent(templateName))+"&totalMark="+totalMark,
??? ??? ??? ??? dataType : "json",
??? ??? ??? ??? success : function(data){
??? ??? ??? ??? ??? alert("111"+data.state);
??? ??? ???????????
??? ??? ??? ??? }
??? ??? ??? });
??????????
??????????
?????????? }

?

2. java后台

/**
??? ?* 添加试卷模板前,判断模板相关属性要求
??? ?*
??? ?* @return
??? ?*/
??? public String checkPaperTemplate() {

??? ??? try {
??? ??? ???
??? ??? ??? // 获取模板名称和模板分数
??? ??? ??? ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
??? ??? ??? int totalMark = Integer.parseInt(ServletActionContext.getRequest()
??? ??? ??? ??? ??? .getParameter("totalMark"));
??? ??? ??? String templateName = java.net.URLDecoder.decode(
??? ??? ??? ??? ??? ServletActionContext.getRequest().getParameter(
??? ??? ??? ??? ??? ??? ??? "templateName"), "utf-8");

??? ??? ??? // 设置检查同名模板的参数
??? ??? ??? HashMap parameter = new HashMap();
??? ??? ??? parameter.put("templateName", templateName);
??? ??? ??? parameter.put("depId", "1201");
??? ??? ???
??? ??? ??? System.out.println("checkPaperTemplate====================totalMark=========="+totalMark+"====" +templateName);

??? ??? ??? // 获取同名模板名称
??? ??? ??? int sameNameCount = paperTemplateService
??? ??? ??? ??? ??? .getSameNameCount(parameter);
??? ??? ??? if (sameNameCount > 0) { // 包含同名的模板信息
??? ??? ??? ??? state = 1;
??? ??? ??? }
??? ??? ??? if (!isMarkEqual(totalMark)) { // 试卷模板总分和模块总分不相等
??? ??? ??? ??? state = 2;
??? ??? ??? }
??? ??? ???
??? ??? ??? System.out.println("state===" + state);

??? ??? ??? return SUCCESS;
??? ??? ???
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();

??? ??? ??? return ERROR;
??? ??? }

??? ???
??? }

3. xml配置文件

<package name="papertemplate_ajax" extends="json-default"
??? ??? namespace="/admin/questionbank_ajax">
??? ??? <!-- 判断添加的试卷模板是否合法 -->
??? ??? <action name="checkPaperTemplate" class="paperTemplateAction"
??? ??? ??? method="checkPaperTemplate">
??? ??? <result type="json"></result>
??? ??? </action>
??? </package>