등록 정보를 제출하기 위해 Ajax를 사용하는 EasyUI 프레임워크의 자세한 예

小云云
풀어 주다: 2017-12-27 10:26:54
원래의
1913명이 탐색했습니다.

이 글은 등록 정보 제출을 위해 Ajax를 사용한 EasyUI 프레임워크 구현 코드에 대한 관련 정보를 주로 소개합니다. 도움이 필요한 모든 분들에게 도움이 되기를 바랍니다.

EasyUI 프레임워크는 Ajax를 사용하여 등록 정보 구현 코드를 제출합니다

1. 서버 코드:


@Controller
@Scope("prototype")
public class StudentAction extends BaseAction<Student> {
  private static final long serialVersionUID = -2612140283476148779L;

  private Logger logger = Logger.getLogger(StudentAction.class);
  private String rows;// 每页显示的记录数
  private String page;// 当前第几页
  private Map<String, Object> josnMap = new HashMap<>();

  // 查询出所有学生信息
  public String list() throws Exception {
    return "list";
  }

  public String regUI() throws Exception {
    return "regUI";
  }

  // 查询出所有学生信息
  public String listContent() throws Exception {
    List<Student> list = studentService.getStudentList(page, rows);
    System.out.println("list==" + list);
    toBeJson(list, studentService.getStudentTotal());
    return "toJson";
  }

  // 转化为Json格式
  public void toBeJson(List<Student> list, int total) throws Exception {
    josnMap.put("total", total);
    josnMap.put("rows", list);
    JSONParser.writeJson(josnMap);// 自定义的工具类
  }

  public String reg(){
    logger.error("kkk");
    try {
      studentService.save(model);
      josnMap.put("success", true);
      josnMap.put("msg", "注册成功!");
    } catch (Exception e) {
      e.printStackTrace();
      josnMap.put("success", false);
      josnMap.put("msg", "注册失败!");
    }
    try {
      ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
      ServletActionContext.getResponse().setCharacterEncoding("utf-8");
      ServletActionContext.getResponse().getWriter().print(JSON.toJSONString(josnMap));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return "toJson";
  }

  public void setRows(String rows) {
    this.rows = rows;
  }

  public void setPage(String page) {
    this.page = page;
  }

  public Map<String, Object> getJosnMap() {
    return josnMap;
  }

  public void setJosnMap(Map<String, Object> josnMap) {
    this.josnMap = josnMap;
  }



}
로그인 후 복사

2. BaseAction 코드:


import java.lang.reflect.ParameterizedType;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;

import cn.oppo.oa.service.DepartmentService;
import cn.oppo.oa.service.ForumService;
import cn.oppo.oa.service.PrivilegeService;
import cn.oppo.oa.service.RoleService;
import cn.oppo.oa.service.StudentService;
import cn.oppo.oa.service.UserService;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  @Resource
  protected RoleService roleService;
  @Resource
  protected DepartmentService departmentService;
  @Resource
  protected UserService userService;
  @Resource
  protected PrivilegeService privilegeService;

  @Resource
  protected ForumService forumService;

  @Resource
  protected StudentService studentService;

  protected T model;

  @SuppressWarnings("unchecked")
  public BaseAction() {
    try {
      // 得到model的类型信息
      ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
      Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];

      // 通过反射生成model的实例
      model = (T) clazz.newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void writeJson(Object object){
    try {
      String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
      ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
      ServletActionContext.getResponse().setCharacterEncoding("utf-8");
      ServletActionContext.getResponse().getWriter().write(json);
      ServletActionContext.getResponse().getWriter().flush();
      ServletActionContext.getResponse().getWriter().close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public T getModel() {
    return model;
  }
}
로그인 후 복사

3. 페이지 코드:


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
  <title>EasyUI框架</title>
  <%@ include file="/WEB-INF/jsp/public/common.jspf" %>
  <script type="text/javascript">
     $(function(){
       if(${"#easyui_regForm"}.form(&#39;validate&#39;)){
         $.ajax({
           url:&#39;${pageContext.request.contextPath}/student_reg.action&#39;,
           data:${"#easyui_regForm"}.serialize(),
           dataType:&#39;json&#39;,
           success:function(obj,status,jqXHR){
             if(obj.success){
               $("#easyui_regDialog").dialog(&#39;close&#39;);
             }
             $.message.show({
              title:&#39;提示&#39;,
              msg:obj.msg
             });
           }
         });
       }else{
         alert(&#39;验证失败&#39;);
       }
    }); 
  </script>
</head>
<body class="easyui-layout">
  <p data-options="region:&#39;north&#39;,split:true" style="height:100px;">aa</p>
  <!-- <p data-options="region:&#39;south&#39;,split:true" style="height:100px;">bb</p>-->
  <p data-options="region:&#39;east&#39;,title:&#39;East&#39;,split:true" style="width:200px;">cc</p> 
  <p data-options="region:&#39;west&#39;,title:&#39;West&#39;,split:true" style="width:200px;">dd</p>
  <p data-options="region:&#39;center&#39;,title:&#39;center title&#39;" style="padding:5px;background:#eee;">kk</p>

  <p class="easyui-dialog" data-options="title:&#39;登陆&#39;, modal:true,
      closable:false,
      toolbar:[{
        text:&#39;Edit&#39;,
        iconCls:&#39;icon-edit&#39;,
        handler:function(){alert(&#39;edit&#39;)}
      },{
        text:&#39;Help&#39;,
        iconCls:&#39;icon-help&#39;,
        handler:function(){alert(&#39;help&#39;)}
      }],
      buttons:[{
        text:&#39;登陆&#39;,
        handler:function(){alert(&#39;登陆&#39;)}
      },{
        text:&#39;注册&#39;,
        handler:function(){
          $(&#39;#easyui_regForm input&#39;).val(&#39;&#39;);
          $(&#39;#easyui_regDialog&#39;).dialog(&#39;open&#39;);
        }
      }]" >
    <table>
      <tr>
        <td>登陆名称:</td>
        <td><input type="text" name="name"/></td>
      </tr>
      <tr>
        <td>登陆密码:</td>
        <td><input type="password" name="password"/></td>
      </tr>
    </table>
  </p>

  <p id="easyui_regDialog" class="easyui-dialog" data-options="title:&#39;注册&#39;, modal:true,
      closable:true,
      closed:true,
      buttons:[{
        text:&#39;注册&#39;,
        handler:function(){
          $(&#39;#easyui_regForm&#39;).form(&#39;submit&#39;,{
          url : &#39;${pageContext.request.contextPath}/student_reg.action&#39;,
          success : function(data) {
            var obj = jQuery.parseJSON(data);
            if (obj.success) {
              $(&#39;#easyui_regDialog&#39;).dialog(&#39;close&#39;);
            }
            $.messager.show({
              title : &#39;提示&#39;,
              msg : obj.msg
            });
          }
      });
        }
      },{
        text:&#39;取消&#39;,
        handler:function(){alert(&#39;注册&#39;)}
      }]" >
    <form id="easyui_regForm" method="post">
    <table>
      <tr>
        <td>登陆名称:</td>
        <td><input type="text" name="loginName" class="easyui-validatebox" data-options="required:true,missingMessage:&#39;用户名称不能为空&#39;"/></td>
      </tr>
      <tr>
        <td>登陆密码:</td>
        <td><input id="reg_pwd" type="password" name="password" class="easyui-validatebox" data-options="required:true,missingMessage:&#39;用户密码不能为空&#39;"/></td>
      </tr>
      <tr>
        <td>确定密码:</td>
        <td><input type="password" name="repassword" class="easyui-validatebox" data-options="required:true,missingMessage:&#39;确认密码不能为空&#39;,validType:&#39;equals[\&#39;#reg_pwd\&#39;]&#39;" /></td>
      </tr>
    </table>
    </form>
  </p>
</body>
</html>
로그인 후 복사
re iv. struts2.xml 구성

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <!-- 配置为开发模式 -->
  <constant name="struts.devMode" value="true" />
  <!-- 配置扩展名为action -->
  <constant name="struts.action.extension" value="action" />
  <!-- 配置主题 -->
  <constant name="struts.ui.theme" value="simple" />

  <package name="default" namespace="/" extends="json-default">

    <interceptors>
      <!-- 声明一个拦截器 -->
      <interceptor name="checkePrivilege" class="cn.oppo.oa.interceptor.CheckPrivilegeInterceptor"></interceptor>

      <!-- 重新定义defaultStack拦截器栈,需要先判断权限 -->
      <interceptor-stack name="defaultStack">
        <interceptor-ref name="checkePrivilege" />
        <interceptor-ref name="defaultStack" />
      </interceptor-stack>
    </interceptors>


    <!-- 配置全局的Result -->
    <global-results>
      <result name="loginUI">/WEB-INF/jsp/user/loginUI.jsp</result>
      <result name="noPrivilegeError">/noPrivilegeError.jsp</result>
    </global-results>


    <!-- 测试用的action,当与Spring整合后,class属性写的就是Spring中bean的名称 -->
    <action name="test" class="testAction">
      <result name="success">/test.jsp</result>
    </action>


    <action name="*_*" class="{1}Action" method="{2}">
      <result name="{2}">/WEB-INF/jsp/{1}/{2}.jsp</result>
      <!-- 跳转到添加与修改页面 -->
      <result name="saveUI">/WEB-INF/jsp/{1}/saveUI.jsp</result>
      <!-- 返回list页 -->
      <result name="toList" type="redirectAction">{1}_list?parentId=${parentId}</result>
      <!-- 返回主页 -->
      <result name="toIndex" type="redirect">/index.jsp</result>
      <!-- 返回论坛主题 -->
      <result name="toShow" type="redirectAction">topic_show?id=${id}</result>
      <result name="toTopicShow" type="redirectAction">topic_show?id=${topicId}</result>
      <!-- json解析 -->
      <result name="toJson" type="json">
        <param name="root">josnMap</param>
      </result>

      <result name="reg">/easyui.jsp</result>


    </action>

  </package>

</struts>
로그인 후 복사
관련 추천 :


PHP 사용자 등록 정보 샘플 코드를 확인하기 위해 사용자 등록 정보가 법적 _php인지 확인합니다. Tutorial

탐색바 + 등록정보_html/css_WEB-ITnose

위 내용은 등록 정보를 제출하기 위해 Ajax를 사용하는 EasyUI 프레임워크의 자세한 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!