How does Json-lib handle when using Ajax
This time I will show you how to handle Json-lib when using Ajax. What are the precautions for Json-lib processing when using Ajax? The following is a practical case, let's take a look.
Whether you are using ajax or easyui and other frameworks, the problem of json processing is involved when the background outputs data to the front. Here are two processing methods. The first is to manually configure the json processing method, and the other is to manually configure the json processing method. A solution using json-lib. The ordinary manual configuration method is clumsy. It needs to be configured one by one according to the field name each time, so it cannot be used on other objects, which reduces the reusability of the code. The json-lib tool can be used to achieve automatic processing and different processing for different objects. Measures have greatly improved the processing efficiency and code reusability. The processes of the two methods are introduced below based on cases: Method 1: Ordinary method, through the process of manual configuration transformation, request with easyui's jsp page:<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>
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); }
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; } }
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>
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); }
/** * 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("'"+properties[i]+"':'"+v+"'"); json.append(i != properties.length-1?",":""); } json.append("}"); }catch (Exception e) { e.printStackTrace(); } return JSONObject.fromObject(json.toString()); } }
Use history to enable ajax to support forward/back/refresh
Ajax method to implement Form form submission
The above is the detailed content of How does Json-lib handle when using Ajax. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object
