使用Jquery-easyUI的datagrid从后台加载数据不成功的解决办法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Jquery-easyUI的datagrid从后台加载数据不成功的解决办法相关的知识,希望对你有一定的参考价值。

最近在用easyUI做一个注册页面总是出现从后台数加载不成功的问题,后来在一个师兄的指导下通过debug模式终于发现问题并解决了,以下记录我解决这一问题的过程。开发环境:jdk1.7,工具:eclipse,框架:spring-mvc

 spring-mvc的配置代码

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <!-- 开启注解功能 -->
    <mvc:annotation-driven validator="validator" />

    <!-- 开启组件扫描 @controller @service @compent -->
    <context:component-scan base-package="com.zsrt">
    </context:component-scan>
    <!-- 配置视图解析器 -->
    <bean id="internalResourceViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp的前缀 /代表 webContent -->
        <property name="prefix" value="/WEB-INF/pages/">
        </property>
        <property name="suffix" value=".jsp">
        </property>
    </bean>

    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- 上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

    <!-- 服务器端验证 -->
    <bean id="validatemessageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:validatemessages" />
        <property name="fileEncodings" value="utf-8" />
        <property name="cacheSeconds" value="120" />
    </bean>
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="validatemessageSource" />
    </bean>

    <!-- 拦截器 
    <mvc:interceptors>
        
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.zsrt.intercepter.AuthHandlerInterceptor"></bean>

        </mvc:interceptor>
        
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.zsrt.intercepter.AuthHandlerInterceptor2"></bean>

        </mvc:interceptor>
    </mvc:interceptors>-->
</beans>

spring-mybatis的配置代码

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <!-- 开启注解功能 -->
    <mvc:annotation-driven validator="validator" />

    <!-- 开启组件扫描 @controller @service @compent -->
    <context:component-scan base-package="com.zsrt">
    </context:component-scan>
    <!-- 配置视图解析器 -->
    <bean id="internalResourceViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp的前缀 /代表 webContent -->
        <property name="prefix" value="/WEB-INF/pages/">
        </property>
        <property name="suffix" value=".jsp">
        </property>
    </bean>

    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- 上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

    <!-- 服务器端验证 -->
    <bean id="validatemessageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:validatemessages" />
        <property name="fileEncodings" value="utf-8" />
        <property name="cacheSeconds" value="120" />
    </bean>
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="validatemessageSource" />
    </bean>

    <!-- 拦截器 
    <mvc:interceptors>
        
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.zsrt.intercepter.AuthHandlerInterceptor"></bean>

        </mvc:interceptor>
        
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean class="com.zsrt.intercepter.AuthHandlerInterceptor2"></bean>

        </mvc:interceptor>
    </mvc:interceptors>-->
</beans>

 

以下为实体类代码:

package com.zsrt.entity;

import javax.persistence.Table;

@Table(name="person_info")
public class PersonInfoDTO {

    private String id;
    private String name;
    private String sex;
    private String province;//
    private String city;//
    private String phone;
    private String accNum;
    private String email;
    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAccNum() {
        return accNum;
    }
    public void setAccNum(String accNum) {
        this.accNum = accNum;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "PersonInfoDTO [id=" + id + ", name=" + name + ", sex=" + sex + ", province=" + province + ", city="
                + city + ", phone=" + phone + ", accNum=" + accNum + ", email=" + email + "]";
    }

}
package com.zsrt.entity;

import java.util.Date;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class Emp {
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    private Integer empid;    
    private String accNum;
    private String accPass;
    private String empName;
    private String empPhone;
    
    private Date birthday;
    private Integer deptid ;
    private Integer roleid;
    private String email;
    
    public Integer getEmpid() {
        return empid;
    }
    public void setEmpid(Integer empid) {
        this.empid = empid;
    }
    public String getAccNum() {
        return accNum;
    }
    public void setAccNum(String accNum) {
        this.accNum = accNum;
    }
    public String getAccPass() {
        return accPass;
    }
    public void setAccPass(String accPass) {
        this.accPass = accPass;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public String getEmpPhone() {
        return empPhone;
    }
    public void setEmpPhone(String empPhone) {
        this.empPhone = empPhone;
    }
    public Integer getDeptid() {
        return deptid;
    }
    public void setDeptid(Integer deptid) {
        this.deptid = deptid;
    }
    public Integer getRoleid() {
        return roleid;
    }
    public void setRoleid(Integer roleid) {
        this.roleid = roleid;
    }
    
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "Emp [empid=" + empid + ", accNum=" + accNum + ", accPass=" + accPass + ", empName=" + empName
                + ", empPhone=" + empPhone + ", birthday=" + birthday + ", deptid=" + deptid + ", roleid=" + roleid
                + ", email=" + email + "]";
    }
    
    
}

Emp的扩展类

package com.zsrt.entity;

public class EmpCustom extends Emp{
private int nextRoleid;
private String roleName;
public int getNextRoleid() {
return nextRoleid;
}
public void setNextRoleid(int nextRoleid) {
this.nextRoleid = nextRoleid;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
package com.zsrt.entity;

import javax.persistence.Table;
public class DictDTO {
    private String id;
    private String itemCode;
    private String itemName;
    private String typeCode;
    private String status;
    private String parentCode;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getItemCode() {
        return itemCode;
    }
    public void setItemCode(String itemCode) {
        this.itemCode = itemCode;
    }
    public String getItemName() {
        return itemName;
    }
    public void setItemName(String itemName) {
        this.itemName = itemName;
    }
    public String getTypeCode() {
        return typeCode;
    }
    public void setTypeCode(String typeCode) {
        this.typeCode = typeCode;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getParentCode() {
        return parentCode;
    }
    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }

    
    
}

personInfoDTO在数据库中对应的表,表明为person_info

技术分享

Emp类在数据库中对应的表,表命名为oa_emp

技术分享

 dict字典表

技术分享

插入数据后

技术分享

技术分享

技术分享

 技术分享

技术分享

技术分享

技术分享

技术分享

由于数据库内容太多,而sql语句没有及时保存,所以就不一一截图了,插入数据的原理是属于一个省的城市其parentCode为该省所对应的itemCode

 DAO层代码

package com.zsrt.emp.dao;

import java.util.List;

import com.zsrt.entity.PersonInfoDTO;

/**
 * personinfoDAO
 * @author leixin
 * @Date 2017年5月22日
 * @version 1.0
 */
public interface PersonInfoDAO {
    
    int insert(PersonInfoDTO personInfoDTO);

    List<PersonInfoDTO> selectByPerson(PersonInfoDTO personInfoDTO);
    
    PersonInfoDTO checkAccNum(String accNum);
    
    
}
package com.zsrt.emp.dao;

import java.util.List;

import com.zsrt.entity.DictDTO;

/**
 * 字典表DAO
 * @author leixin
 * @Date 2017年5月22日
 * @version 1.0
 */
public interface DictDAO {
    
    List<DictDTO> selectByDictDTO(DictDTO dictDTO);
    
    String queryItemName(String itemCode);
}

Mapper层代XML码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsrt.emp.dao.DictDAO">
    <select id="selectByDictDTO" parameterType="com.zsrt.entity.DictDTO"
    resultType="com.zsrt.entity.DictDTO">
        SELECT * FROM `dict`
        WHERE 1=1 
        <if test="typeCode !=null and typeCode != ‘‘">
            AND typeCode = #{typeCode}
        </if>
        <if test="parentCode !=null and parentCode != ‘‘">
            AND parentCode = #{parentCode}
        </if>
    </select>
    
    <select id="queryItemName" parameterType="java.lang.String" resultType="java.lang.String">
        SELECT itemName FROM `dict` WHERE itemCode=#{itemCode}
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zsrt.emp.dao.PersonInfoDAO">
    <resultMap type="com.zsrt.emp.dao.PersonInfoDAO" id="personMap">
        <id column="id" property="id"></id>
        <result column="accNum" property="accNum"></result>
        <result column="name" property="name"></result>
        <result column="sex" property="sex"></result>
        <result column="province" property="province"></result>
        <result column="city" property="city"></result>
        <result column="phone" property="phone"></result>
        <result column="email" property="email"></result>
   </resultMap>

    <insert id="insert" parameterType="com.zsrt.entity.PersonInfoDTO">
        INSERT INTO `person_info` (
            `id`,
            `name`,
            `sex`,
            `province`,
            `city`,
            `phone`,
            `accNum`,
            `email`
        )
        VALUES
            (
                #{id},
                #{name},
                #{sex},
                #{province},
                #{city},
                #{phone},
                #{accNum},
                #{email}
            )
    </insert>
    
    <select id="selectByPerson" parameterType="com.zsrt.entity.PersonInfoDTO" 
    resultMap="personMap">
        SELECT
            `id`,`name`,`sex`,`province`,`city`,`phone`,`accNum`,`email`
        WHERE
            1 = 1
        <if test="name != null and name !=‘‘ ">
            AND `name` = #{name}
        </if>
        <if test="phone !=null and phone !=‘‘">
            AND phone = #{phone}
        </if>    
    </select>
    <!-- 检查注册账号是否重复 -->
    <select id="checkAccNum" parameterType="java.lang.String" resultType="com.zsrt.entity.PersonInfoDTO">
        SELECT * FROM person_info WHERE accNum=#{accNum} 
    </select>
    
</mapper>

Service层代码

package com.zsrt.emp.service;

import java.util.List;

import com.zsrt.entity.DictDTO;

public interface DictService {

    List<DictDTO> selectByDictDTO(DictDTO dictDTO);
    
    String queryItemName(String itemCode);
}

package com.zsrt.emp.service;

import java.util.List;
import java.util.Map;

import com.zsrt.entity.PersonInfoDTO;

public interface PersonInfoService {

    Map<String, Object> insert(PersonInfoDTO personInfoDTO);

    List<PersonInfoDTO> selectByPerson(PersonInfoDTO personInfoDTO);
    
    PersonInfoDTO checkAccNum(String accNum);
}

对应的服务层实现类

package com.zsrt.emp.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zsrt.emp.dao.DictDAO;
import com.zsrt.emp.service.DictService;
import com.zsrt.entity.DictDTO;
@Service
public class DictServiceImpl implements DictService{

    @Resource
    private DictDAO dictDAO;
    
    @Override
    public List<DictDTO> selectByDictDTO(DictDTO dictDTO) {
        
        return dictDAO.selectByDictDTO(dictDTO);
    }

    @Override
    public String queryItemName(String itemCode) {
        
        return dictDAO.queryItemName(itemCode);
    }

}
package com.zsrt.emp.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zsrt.emp.dao.DictDAO;
import com.zsrt.emp.service.DictService;
import com.zsrt.entity.DictDTO;
@Service
public class DictServiceImpl implements DictService{

    @Resource
    private DictDAO dictDAO;
    
    @Override
    public List<DictDTO> selectByDictDTO(DictDTO dictDTO) {
        
        return dictDAO.selectByDictDTO(dictDTO);
    }

    @Override
    public String queryItemName(String itemCode) {
        
        return dictDAO.queryItemName(itemCode);
    }

}
发生错误前控制层代码

package com.zsrt.emp.controller;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zsrt.emp.service.DictService;
import com.zsrt.emp.service.EmpService;
import com.zsrt.emp.service.PersonInfoService;
import com.zsrt.entity.PersonInfoDTO;

@Controller
@RequestMapping(value="/person")
public class PersonInfoController {
    @Resource
    private PersonInfoService personInfoService;
    
    @Resource
    private DictService dictService;
    
    @Resource
    private EmpService empService;
    
    @RequestMapping(value="/init")
    public String init() {
        return "person";
    }
    
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String, Object> list(PersonInfoDTO personInfoDTO){
        Map<String, Object> result = new HashMap<>();
        List<PersonInfoDTO> list = personInfoService.selectByPerson(personInfoDTO);
        result.put("rows", list);
        result.put("total", 100);
        System.err.println(result.toString());
        return result;
    }
    
    @RequestMapping(value="/save")
    @ResponseBody
    public Map<String, Object> save(PersonInfoDTO personInfoDTO,Model model){
        personInfoDTO.setId(UUID.randomUUID().toString().replace("-", ""));
        String provinceCode=personInfoDTO.getProvince();
        String province=dictService.queryItemName(provinceCode);
        personInfoDTO.setProvince(province); 
        String cityCode=personInfoDTO.getCity();
        String city=dictService.queryItemName(cityCode);
        personInfoDTO.setCity(city);
        Map<String, Object> result = personInfoService.insert(personInfoDTO);
        System.out.println(personInfoDTO.toString());
        Map<String,Object> personInfoMap=new HashMap<>();
        if(result.containsKey("success")){
            
            if(null==personInfoDTO.getPhone()||"".equals(personInfoDTO.getPhone())){
                String phone=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmpPhone();
                personInfoDTO.setPhone(phone);
            }
            if(null==personInfoDTO.getEmail()|| "".equals(personInfoDTO.getEmail())){
                String email=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmail();
            }
            List<PersonInfoDTO> personList=new ArrayList<PersonInfoDTO>();
            personList.add(personInfoDTO);
            personInfoMap.put("rows", personList);
            personInfoMap.put("total", 10);
            model.addAttribute("personInfoMap",JSON.toJSONString(personInfoMap));
        System.out.println("个人信息JSON字符窜:"+JSON.toJSONString(personInfoMap));
            
        }
        return result;
    }
    
    @RequestMapping(value="/checkAccNum")
    @ResponseBody
    public Object checkAccNum(String accNum){
        PersonInfoDTO personInfo=personInfoService.checkAccNum(accNum);
        Map<String,Object> result=new HashMap<>();
        System.out.println("注册帐号wei:"+accNum);
        
        if(null==personInfo){
            result.put("success", "帐号可用");
        }
        else{
            System.out.println("是否重复信息"+personInfo.toString());
            result.put("error", "帐号重复,不能注册");
        }
        return result;
        
    }
    
    @RequestMapping(value="/showPersonInfo")
    public String showPersonInfo(){
        
        return "PersonReg";
    }
    
    
    
}

前台注册页面代码,需求如下

前提条件:
1.在现有项目的基础上做
2.给person_info表中增加一个accNum字段,表示两张表的关联关系
3.给oa_emp表中增加邮箱字段,同时在person_info表中增加邮箱字段


1.做一个注册功能,注册采用手机号,注册成功之后跳转到个人信息页面,
并且显示个人信息,若注册失败,则页面显示错误消息 (20分)

2.个人信息显示中手机号和邮箱的两种情况:
a.person_info表中没有手机号和邮箱信息,将oa_emp中的信息取出显示在页面上 (20分)
b.person_info表中有手机号和邮箱信息,直接显示person_info表中的信息 (20分)
将性别、省市、正确显示在页面上 (20分)

公共样式 common.jsp文件代码

<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<% String context = request.getContextPath();%>
<script type="text/javascript"> 
    var contextPath=<%=context%>;    
</script>
<script type="text/javascript" src="<%=context%>/js/jquery-easyui/jquery.min.js"></script>
<script type="text/javascript" src="<%=context%>/js/jquery-easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="<%=context%>/js/jquery-easyui/locale/easyui-lang-zh_CN.js" charset="utf-8"></script>
<link rel="stylesheet" href="<%=context%>/js/jquery-easyui/themes/default/easyui.css" />
<link rel="stylesheet" href="<%=context%>/js/jquery-easyui/themes/icon.css" />

注册页面reg.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册页面</title>

<script type="text/javascript">
    
    
   /* $.extend($.fn.validatebox.defaults.rules, {    
        testAccNum: {    
            validator: function(value, param){
                var reg1=/^[1][3,4,5,7,8]\\d{9}$/;
                var reg2=/^[a-zA-Z0-9_]{3,}@[a-z0-9]{2,6}.[a-z]{2,4}([a-z]{2})?$/;
                return  param[reg1].test(value) || param[reg2].test(value); 
            },    
            message: ‘注册帐号格式不正确.‘   
        },
        testPhone:{
            validator:function(value,param){
                var reg=/^[1][3,4,5,7,8]\\d{9}$/;
                return param[reg].test(value);
            },
            message:‘手机号码格式错误.‘
        }
    });*/  
    
    
    $(function(){
            $("input",$(#accNum).next("span")).blur(function(){
            var accNum=$(#accNum).val();
            console.log(accNum);
            if(accNum==‘‘){
                $(#accNumSpan).html("<font color=‘red‘>注册帐号不能为空!</font>"); 
                return false;
            }
            var reg1=/^[1][3,4,5,7,8]\\d{9}$/;
            var reg2=/^[a-zA-Z0-9_]{3,}@[a-z0-9]{2,6}.[a-z]{2,4}([a-z]{2})?$/;
            if(!reg1.test(accNum) && !reg2.test(accNum)){
               $(#accNumSpan).html("<font color=‘red‘>注册帐号不是手机号或邮箱!</font>");
                 return false;
            }
            //验证z注册帐号是否重复
            $.ajax({
                url:${pageContext.request.contextPath}/person/checkAccNum,
                type:POST,
                data:{"accNum":accNum},
                dataType:json,
                success:function(data){
                    var obj=JSON.parse(data);
                    if(obj.success){
                        console.log(obj.success);
                       $(#accNumSpan).html("<font color=‘green‘>帐号可用</font>"); 
                    }
                    else{
                       console.log(obj.error);
                       $(#accNumSpan).html("<font color=‘red‘>帐号重复,不可用</font>");
                       return false;
                    }
                }
            });  //end ajax 
            
            
        });   //end accNumblur()
        
       $("input",$(#accNum).next("span")).focus(function(){
           $.messager.show({
               title:提示信息,
               msg:帐号请优先选择您的手机号码,其次也可选择您的邮箱,
               timeout:5000,
               showType:slide
               
           });
        $(#accNumSpan).html("<font color=‘green‘>&nbsp;</font>");
        
       }); 
        
           /*var sex=$(‘:input[name="sex"]:checked‘).val();
           console.log(sex); */
           
  });
    
    /*var checkPhone=function(){
        $("input",$(‘#phone‘).next("span")).blur(function(){
            var phone=$(‘#phone‘).val();
            if(phone==‘‘){
                $(‘phoneSpan‘).html("<font color=‘red‘>手机号为空</font>");
                
            }
            else{
                console.log(phone);
            }
            
            
        });
    }*/
    
    
 
    var register=function(){
        $(#regForm).form(submit,{
            url:${pageContext.request.contextPath}/person/save,
            
            onSubmit:function(){
                
                return true;    
                
            }, //end onSubmit
            success:function(data){
                var dataObj=JSON.parse(data);
                if(dataObj.success){
                    console.log(dataObj.success);
                    self.location=contextPath+"/person/showPersonInfo";
                }
                else{
                    alert("注册失败!");
                }
                
                
            }//end success
            
                
            
        }); //end form
        
    }//end register
    

</script>
</head>
<body>
<div align="center" style="margin-top:120px;">
    <div class="esayui-panel" title="注册" style="width:400px;height:800px;" data-options="border:false">
    <form name="regForm" id="regForm" method="post" action="">
        <table style="margin-top:40px;" align="center">
            <tr>
                <td>账号:</td>
                <td><input id="accNum" name="accNum" class="easyui-textbox" data-options="required:true,icoCls:‘icon-man‘"><span id="accNumSpan"></span>
                </td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td><input calss="easyui-textbox" name="name"/><span id="nameSpan"></span></td>
            </tr>
            <tr>
                <td>性别:</td>
                <td><input type="radio" name="sex" value="M"/><input type="radio" name="sex" value="F"/></td>
            </tr>
                <td>省:</td>
                <td><select name="province" class="easyui-combobox" style="width: 173px"
                    data-options="valueField:‘itemCode‘,textField:‘itemName‘,url:‘${pageContext.request.contextPath}/dict/selectList?typeCode=region_province‘,
                     onSelect: function(data){  
                             console.info(data);
                             $(‘#city‘).combobox(‘clear‘);
                             var url = ‘${pageContext.request.contextPath}/dict/selectList?typeCode=region_city&parentCode=‘+data.itemCode;
                             console.log(data.itemCode);
                             $(‘#city‘).combobox(‘reload‘,url);
                        }">
                    </select>
                </td>
            <tr>
                <td>市:</td>
                <td>
                  <select id="city" name="city" class="easyui-combobox" style="width: 173px"
                      data-options="valueField:‘itemCode‘,textField:‘itemName‘">
                  </select>
                </td>
            </tr>
            <tr>
                <td>手机号码:</td>
                <td><input id="phone" name="phone" class="easyui-textbox" ><span id="phoneSpan"></span></td>
            </tr>
            <tr>
                <td>邮箱:</td>
                <td><input name="email" class="easyui-validatebox" validType="email" invalidMessage="邮箱格式错误!"/></td>
            </tr>
            <tr>
               <td><a class="easyui-linkbutton" data-options="iconCls:‘icon-ok‘" onclick="register()">注册</a></td>
               <td align="right"><input type="reset" name="reset" value="重置"></td>
            </tr>
        </table>
    </form>
    </div>
</div>
</body>
</html>

跳转页面PersonReg.jsp文件代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../../common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>个人注册信息</title>
<script type="text/javascript">
    $(document).ready(function(){
        var obj=${personInfoMap};
        $(#dg).datagrid(loadData,obj);
    });
    
    var closeDialog=function(){
        $(#editDialog).dialog(close);
    }
    var openDialog=function(){
        console.log(111);
        $(#editDialog).dialog(open);
    }
    
   var save=function(){
        
    }
    //验证内容
    $(function(){
           $("input",$(#accNum).next("span")).blur(function(){
           var accNum=$(#accNum).val();
           console.log(accNum);
           if(accNum==‘‘){
               $(#accNumSpan).html("<font color=‘red‘>注册帐号不能为空!</font>"); 
               return false;
           }
           var reg1=/^[1][3,4,5,7,8]\\d{9}$/;
           var reg2=/^[a-zA-Z0-9_]{3,}@[a-z0-9]{2,6}.[a-z]{2,4}([a-z]{2})?$/;
           if(!reg1.test(accNum) && !reg2.test(accNum)){
              $(#accNumSpan).html("<font color=‘red‘>注册帐号不是手机号或邮箱!</font>");
                return false;
           }
           //验证z注册帐号是否重复
           $.ajax({
               url:${pageContext.request.contextPath}/person/checkAccNum,
               type:POST,
               data:{"accNum":accNum},
               dataType:json,
               success:function(data){
                   
                   if(data.success){
                       console.log(data.success);
                      $(#accNumSpan).html("<font color=‘green‘>帐号可用</font>"); 
                   }
                   else{
                      console.log(data.error);
                      $(#accNumSpan).html("<font color=‘red‘>帐号重复,不可用</font>");
                      return false;
                   }
               }
           });  //end ajax 
           
           
       });   //end accNumblur()
       
      $("input",$(#accNum).next("span")).focus(function(){
          $.messager.show({
              title:提示信息,
              msg:帐号请优先选择您的手机号码,其次也可选择您的邮箱,
              timeout:5000,
              showType:slide
              
          });
       $(#accNumSpan).html("<font color=‘green‘>&nbsp;</font>");
       
      }); 
       
          /*var sex=$(‘:input[name="sex"]:checked‘).val();
          console.log(sex); */
          
 });
    
    
    
    
</script>
</head>
<body>
<div class="easyui-panel" title="个人信息显示" align="center" data-options="border:false" >
    
    <table id="dg" align="center" class="easyui-datagrid" data-options="toolbar:‘#tb‘,pagination:true,url:‘‘">
        <thead>   
                <tr> 
                    <th data-options="field:‘ck‘,checkbox:true"></th>  
                    <th data-options="field:‘id‘">id</th>   
                    <th data-options="field:‘accNum‘">accNum</th>   
                    <th data-options="field:‘name‘">name</th>
                    <th data-options="field:‘sex‘">sex</th>
                    <th data-options="field:‘province‘">province</th>
                    <th data-options="field:‘city‘">city</th>
                    <th data-options="field:‘phone‘">phone</th>
                    <th data-options="field:‘email‘">email</th>
                </tr>   
            </thead>
    </table>
</div>
    <div id="tb">
        <a class="easyui-linkbutton" onclick="openDialog()" data-options = "iconCls:‘icon-edit‘">修改个人信息</a>
    </div>
    <div id="dialogButton">
        <a class="easyui-linkbutton" data-options="iconCls:‘icon-cancel‘" onclick="closeDialog()">取消</a>
        <a class="easyui-linkbutton" data-options="iconCls:‘icon-save‘" onclick="save()">保存</a>
    </div>
    <div id="editDialog" class="easyui-dialog" title="修改个人信息" data-options="closed:true,buttons:‘#dialogButton‘" style="width:300px;height:600px;">
        <div class="easyui-panel">
            <form name="editForm" id="editForm" action="" method="post">
                <table style="margin-top:40px;" align="center">
            <tr>
                <td>账号:</td>
                <td><input id="accNum" name="accNum" class="easyui-textbox" data-options="required:true"><span id="accNumSpan"></span>
                </td>
            </tr>
            <tr>
                <td>姓名:</td>
                <td><input calss="easyui-textbox" name="name"/><span id="nameSpan"></span></td>
            </tr>
            <tr>
                <td>性别:</td>
                <td><input type="radio" name="sex" value="M"/><input type="radio" name="sex" value="F"/></td>
            </tr>
                <td>省:</td>
                <td><select name="province" class="easyui-combobox" style="width: 173px"
                    data-options="valueField:‘itemCode‘,textField:‘itemName‘,url:‘${pageContext.request.contextPath}/dict/selectList?typeCode=region_province‘,
                     onSelect: function(data){  
                             console.info(data);
                             $(‘#city‘).combobox(‘clear‘);
                             var url = ‘${pageContext.request.contextPath}/dict/selectList?typeCode=region_city&parentCode=‘+data.itemCode;
                             console.log(data.itemCode);
                             $(‘#city‘).combobox(‘reload‘,url);
                        }">
                    </select>
                </td>
            <tr>
                <td>市:</td>
                <td>
                  <select id="city" name="city" class="easyui-combobox" style="width: 173px"
                      data-options="valueField:‘itemCode‘,textField:‘itemName‘">
                  </select>
                </td>
            </tr>
            <tr>
                <td>手机号码:</td>
                <td><input id="phone" name="phone" class="easyui-textbox" ><span id="phoneSpan"></span></td>
            </tr>
            <tr>
                <td>邮箱:</td>
                <td><input name="email" class="easyui-validatebox" validType="email" invalidMessage="邮箱格式错误!"/></td>
            </tr>
        </table>
    </form>
        </div>
    </div>
    
    ${personInfoMap}
</body>
</html>

以上还有一些功按钮能还没有实现

注册页面效果图

技术分享

 

 跳转后页面加载数据失败效果图

通过debug调试发现前台reg.jsp页面的${personInfoMap}为空,原来是因为Model保存的Map对象 personInfoMap 只能在页面跳转一次的时候才取得到,
而下面这个save方法包含了两次跳转页面,一次是题提交表单时的url请求(url:‘${pageContext.request.contextPath}/person/save‘)
另一次为result返回给success回调函数时的跳转(self.location=contextPath+"/person/showPersonInfo")
解决办法为把 personInfoMap定义为一个全局变量,放到showPersonInfo()方法里

@RequestMapping(value="/save") @ResponseBody public Map<String, Object> save(PersonInfoDTO personInfoDTO,Model model){ personInfoDTO.setId(UUID.randomUUID().toString().replace("-", "")); String provinceCode=personInfoDTO.getProvince(); String province=dictService.queryItemName(provinceCode); personInfoDTO.setProvince(province); String cityCode=personInfoDTO.getCity(); String city=dictService.queryItemName(cityCode); personInfoDTO.setCity(city); Map<String, Object> result = personInfoService.insert(personInfoDTO); System.out.println(personInfoDTO.toString()); if(result.containsKey("success")){ Map<String,Object> personInfoMap=new HashMap<>(); if(null==personInfoDTO.getPhone()||"".equals(personInfoDTO.getPhone())){ String phone=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmpPhone(); personInfoDTO.setPhone(phone); } if(null==personInfoDTO.getEmail()|| "".equals(personInfoDTO.getEmail())){ String email=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmail(); } List<PersonInfoDTO> personList=new ArrayList<PersonInfoDTO>(); personList.add(personInfoDTO); personInfoMap.put("rows", personList); personInfoMap.put("total", 10); model.addAttribute("personInfoMap",JSON.toJSONString(personInfoMap)); System.out.println("个人信息JSON字符窜:"+JSON.toJSONString(personInfoMap)); } return result; }

修改后的PersonInfoController类的代码如下

@Controller
@RequestMapping(value="/person")
public class PersonInfoController {
    @Resource
    private PersonInfoService personInfoService;
    
    @Resource
    private DictService dictService;
    
    @Resource
    private EmpService empService;
    
    Map<String,Object> personInfoMap=new HashMap<>();
    
    @RequestMapping(value="/init")
    public String init() {
        return "person";
    }
    
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String, Object> list(PersonInfoDTO personInfoDTO){
        Map<String, Object> result = new HashMap<>();
        List<PersonInfoDTO> list = personInfoService.selectByPerson(personInfoDTO);
        result.put("rows", list);
        result.put("total", 100);
        System.err.println(result.toString());
        return result;
    }
    
    @RequestMapping(value="/save")
    @ResponseBody
    public Map<String, Object> save(PersonInfoDTO personInfoDTO){
        personInfoDTO.setId(UUID.randomUUID().toString().replace("-", ""));
        String provinceCode=personInfoDTO.getProvince();
        String province=dictService.queryItemName(provinceCode);
        personInfoDTO.setProvince(province);
        String cityCode=personInfoDTO.getCity();
        String city=dictService.queryItemName(cityCode);
        personInfoDTO.setCity(city);
        
        Map<String, Object> result = personInfoService.insert(personInfoDTO);
        System.out.println(personInfoDTO.toString());
        if(result.containsKey("success")){
            
            if(null==personInfoDTO.getPhone()||"".equals(personInfoDTO.getPhone())){
                String phone=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmpPhone();
                personInfoDTO.setPhone(phone);
            }
            if(null==personInfoDTO.getEmail()|| "".equals(personInfoDTO.getEmail())){
                String email=empService.queryEmpByAccnum(personInfoDTO.getAccNum()).getEmail();
            }
            List<PersonInfoDTO> personList=new ArrayList<PersonInfoDTO>();
            personList.add(personInfoDTO);
            personInfoMap.put("rows", personList);
            personInfoMap.put("total", 10);
            
        }
        return result;
    }
    
    @RequestMapping(value="/checkAccNum")
    @ResponseBody
    public Object checkAccNum(String accNum){
        PersonInfoDTO personInfo=personInfoService.checkAccNum(accNum);
        Map<String,Object> result=new HashMap<>();
        System.out.println("注册帐号wei:"+accNum);
        
        if(null==personInfo){
            result.put("success", "帐号可用");
        }
        else{
            System.out.println("是否重复信息"+personInfo.toString());
            result.put("error", "帐号重复,不能注册");
        }
        return result;
        
    }
    
    @RequestMapping(value="/showPersonInfo")
    public String showPersonInfo(Model model){
        model.addAttribute("personInfoMap",JSON.toJSONString(personInfoMap));
        System.out.println("个人信息JSON字符窜:"+JSON.toJSONString(personInfoMap));
        return "PersonReg";
} }

修改后的效果图如下:

技术分享

必须要注意的时用加载到easyui-datagrid的表格里去时后台传递数据时必须用JSON格式,后台控制层结果列表personList作为rows键的value值,回到前台再把personINfoMap转为Jquery对象${personInfoMap}才能去除加载到datagrid表格里去

 



















以上是关于使用Jquery-easyUI的datagrid从后台加载数据不成功的解决办法的主要内容,如果未能解决你的问题,请参考以下文章

jquery-easyui的datagrid(树表),复选框怎么半选?

jquery-easyui 中表格的行编辑功能

Jquery-Easyui的combogrid怎么设置默认值

Easyui datagrid 实现表格记录拖拽

Easyui datagrid 扩展单元格textarea editor

[转]jQuery EasyUI自定义DataGrid的Editor