Heim > Web-Frontend > js-Tutorial > Hauptteil

Json-lib-Verarbeitungslösung bei Verwendung von Frameworks wie Ajax oder Easyui (grafisches Tutorial)

亚连
Freigeben: 2018-05-22 11:13:33
Original
1381 Leute haben es durchsucht

In diesem Artikel wird hauptsächlich die Json-lib-Verarbeitungslösung bei der Verwendung von Ajax oder Easyui und anderen Frameworks vorgestellt. Freunde in Not können sich darauf beziehen.

Ob bei der Verwendung von Ajax oder Easyui und anderen Frameworks, die Hintergrundausgabe erfolgt an das Frontend Daten beinhalten die JSON-Verarbeitung. Die erste besteht darin, die JSON-Verarbeitung manuell zu konfigurieren, und die andere ist die Verwendung von JSON-Lib. Die normale manuelle Konfigurationsmethode ist umständlich. Sie muss jedes Mal einzeln entsprechend dem Feldnamen konfiguriert werden, sodass sie nicht für andere Objekte verwendet werden kann, was die Wiederverwendbarkeit des Codes verringert Die Verarbeitung und unterschiedliche Verarbeitung verschiedener Objekte haben die Verarbeitungseffizienz und die Wiederverwendbarkeit des Codes erheblich verbessert. Nachfolgend werden die Prozesse der beiden Methoden anhand von Fällen vorgestellt:

Methode 1: Gewöhnliche Methode, durch den manuellen Prozess Am Beispiel der Konfigurationstransformation fordert das Frontend Benutzerlistendaten vom Backend über Dategrid an. Die Daten enthalten normale Felddaten (int, String). >jsp-Seite:

<table id="dg" title="用户管理" class="easyui-datagrid"
 fitColumns="true" pagination="true" rownumbers="true"
 url="${pageContext.request.contextPath}/user_list.action" fit="true" toolbar="#tb">
 <thead>
 <tr>
  <th field="cb" checkbox="true" align="center"></th>
  <th field="id" width="50" align="center">编号</th>
  <th field="trueName" width="80" align="center">真实姓名</th>
  <th field="userName" width="80" align="center">用户名</th>
  <th field="password" width="80" align="center">密码</th>
  <th field="sex" width="50" align="center">性别</th>
  <th field="birthday" width="100" align="center">出生日期</th>
  <th field="identityId" width="130" align="center">身份证</th>
  <th field="email" width="120" align="center">邮件</th>
  <th field="mobile" width="80" align="center">联系电话</th>
  <th field="address" width="100" align="center">家庭地址</th>
 </tr>
 </thead>
</table>
Nach dem Login kopieren

**** ******************************* **************** ************************************ ***************** ******************************* ****************

Aktionsebene:

public void list()throws Exception{
 PageBean pageBean=new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
 List<User> userList=userService.findUserList(s_user, pageBean);
 Long total=userService.getUserCount(s_user);
 JSONObject result=new JSONObject();
 JSONArray jsonArray=JsonUtil.formatUserListToJsonArray(userList);
 //easyui接收属性为rows(数据内容)和total(总记录数)
 result.put("rows", jsonArray);
 result.put("total", total);
 //获取response对象
 ResponseUtil.write(ServletActionContext.getResponse(), result);
}
Nach dem Login kopieren

******************** ********************** ************************** ********************* ************************** ************************ ****************

Utility-Tool:

public class JsonUtil {
  /**
   * 将List结果集转化为JsonArray
   * @param gradeService
   * @param stuList
   * @return
   * @throws Exception
   */
  public static JSONArray formatUserListToJsonArray(List<User> userList)throws Exception{
    JSONArray array=new JSONArray();
    for(int i=0;i<userList.size();i++){
      User user=userList.get(i);
      JSONObject jsonObject=new JSONObject(); 
      jsonObject.put("userName", user.getUserName());   //需手动逐个配置json的key-code
      jsonObject.put("password", user.getPassword());
      jsonObject.put("trueName", user.getTrueName());
      jsonObject.put("sex", user.getSex());
      jsonObject.put("birthday", DateUtil.formatDate((user.getBirthday()), "yyyy-MM-dd"));
      jsonObject.put("identityId", user.getIdentityId());
      jsonObject.put("email", user.getEmail());
      jsonObject.put("mobile", user.getMobile());
      jsonObject.put("address", user.getAddress());
      jsonObject.put("id", user.getId());
      array.add(jsonObject);
    }
    return array;
  }
}
Nach dem Login kopieren

Methode 2: Verwenden Sie das jsonLib-Tool, um die Verarbeitung abzuschließen. Nehmen Sie als Beispiel die EasyUI-Anforderungsmethode, und die Rezeption verwendet dategrid. Fordern Sie Produktlistendaten aus dem Hintergrund an. Es gibt normale Felder (int, String). Daten und Datumsdaten (Datum) in den Daten. Gleichzeitig wird das Produktobjekt (Product) auch mit dem Kategorieobjekt (ProductType) kaskadiert

jsp page:

<table id="dg" title="商品管理" class="easyui-datagrid"
fitColumns="true" pagination="true" rownumbers="true"
 url="${pageContext.request.contextPath}/product_list.action" fit="true" toolbar="#tb">
 <thead>
 <tr>
 <th field="cb" checkbox="true" align="center"></th>
 <th field="id" width="50" align="center" hidden="true">编号</th>
 <th field="proPic" width="60" align="center" formatter="formatProPic">商品图片</th>
 <th field="name" width="150" align="center">商品名称</th>
 <th field="price" width="50" align="center">价格</th>
 <th field="stock" width="50" align="center">库存</th>
 <th field="smallType.id" width="100" align="center" formatter="formatTypeId" hidden="true">所属商品类id</th>
 <th field="smallType.name" width="100" align="center" formatter="formatTypeName">所属商品类</th>
 <th field="description" width="50" align="center" hidden="true">描述</th>
 <th field="hotTime" width="50" align="center" hidden="true">上架时间</th>
 </tr>
 </thead>
</table>
Nach dem Login kopieren

** ********************************************** **** ********************************************** *** ********************************************** ** ******

Aktionsebene:

public void list() throws Exception{
 PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
 List<Product> productList=productService.getProducts(s_product, pageBean);
 long total=productService.getProductCount(s_product);
 
 //使用jsonLib工具将list转为json
 JsonConfig jsonConfig=new JsonConfig();
 jsonConfig.setExcludes(new String[]{"orderProductList"}); //非字符串对象不予处理
 jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); //处理日期
 jsonConfig.registerJsonValueProcessor(ProductType.class,new ObjectJsonValueProcessor(new String[]{"id","name"}, ProductType.class)); //处理类别list对象
 JSONArray rows=JSONArray.fromObject(productList, jsonConfig);
 JSONObject result=new JSONObject();
 result.put("rows", rows);
 result.put("total", total);
 ResponseUtil.write(ServletActionContext.getResponse(), result);
}
Nach dem Login kopieren

****************************** ************************************************** * *************************************************** ** *************************

Utility-Tool:

/**
 * json-lib 日期处理类
 * @author Administrator
 *
 */
public class DateJsonValueProcessor implements JsonValueProcessor{
 private String format; 
 
  public DateJsonValueProcessor(String format){ 
    this.format = format; 
  } 
 public Object processArrayValue(Object value, JsonConfig jsonConfig) {
 // TODO Auto-generated method stub
 return null;
 }
 public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
 if(value == null) 
    { 
      return ""; 
    } 
    if(value instanceof java.sql.Timestamp) 
    { 
      String str = new SimpleDateFormat(format).format((java.sql.Timestamp)value); 
      return str; 
    } 
    if (value instanceof java.util.Date) 
    { 
      String str = new SimpleDateFormat(format).format((java.util.Date) value); 
      return str; 
    } 
    return value.toString(); 
 }
}
/**
 * 解决对象级联问题
 * @author Administrator
 *
 */
public class ObjectJsonValueProcessor implements JsonValueProcessor{
 /**
 * 保留的字段
 */
 private String[] properties; 
 
 /**
 * 处理类型
 */
 private Class<?> clazz; 
 
 /**
 * 构造方法 
 * @param properties
 * @param clazz
 */
 public ObjectJsonValueProcessor(String[] properties,Class<?> clazz){ 
    this.properties = properties; 
    this.clazz =clazz; 
  } 
 
 public Object processArrayValue(Object arg0, JsonConfig arg1) {
 // TODO Auto-generated method stub
 return null;
 }
 public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
 PropertyDescriptor pd = null; 
    Method method = null; 
    StringBuffer json = new StringBuffer("{"); 
    try{ 
      for(int i=0;i<properties.length;i++){ 
        pd = new PropertyDescriptor(properties[i], clazz); 
        method = pd.getReadMethod(); 
        String v = String.valueOf(method.invoke(value)); 
        json.append("&#39;"+properties[i]+"&#39;:&#39;"+v+"&#39;"); 
        json.append(i != properties.length-1?",":""); 
      } 
      json.append("}"); 
    }catch (Exception e) { 
      e.printStackTrace(); 
    } 
    return JSONObject.fromObject(json.toString()); 
 }
}
Nach dem Login kopieren

Das Obige ist das, wofür ich kompiliert habe Ich hoffe, dass es in Zukunft für alle hilfreich sein wird.

Verwandte Artikel:

So implementieren Sie die Ajax-Anfragefunktion in JS

PHP-Bootstrap

AjaxFormularübermittlung

ajaxImplementierung einer einfachen Echtzeit-Verifizierungsfunktion

Das obige ist der detaillierte Inhalt vonJson-lib-Verarbeitungslösung bei Verwendung von Frameworks wie Ajax oder Easyui (grafisches Tutorial). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!