Endless Pit: Pages in the Background Eye

Keywords: JSON Session JQuery Javascript

Endless Pit: Pages in the Background Eye

Finally, I finished the first phase of the project. Although the results were good, the process was painful.

Communication with the front desk is more than half of my development time. Eventually abandoned vue.JS because it was compatible with ie 8, abandoned the static page because there were not enough people, even jumped the pit of Iframe, fortunately jumped out again. Next I'm going to post something that interacts with the page. It's all about details. Some may be very specific and simple. I believe that these will be accumulated experience. From this I also made up my mind to add a layer of Node.js to make an attempt to completely separate the front and back. It will be posted after the experiment is successful in a few days.

Reference to a number of net God resources:

http://www.cnblogs.com/zikai/p/5074686.html  
http://www.cnblogs.com/wsw0515/p/3582627.html 
http://www.oschina.net/question/917732_106601 
http://jxd-zxf.iteye.com/blog/2072300 
http://www.tashan10.com/jquery-jiang-biao-dan-xu-lie-hua-wei-jsondui-xiang/                                  

  • 405 (Method Not Allowed) request mode is wrong; ajax request and controller acceptance restriction are different;

//js code
$.ajax({
            type : 'GET',
            url : '<%=basePath%>getDemo?id=' + treeNode.id + '&random=' + Math.random(),
            success : function(data) {}       
        });

//controller code
@RequestMapping(value = "getDemo", method = RequestMethod.GET)
    public String getDemo(String id) {
        return null;
    }
  • HTML encoding and decoding

//HTML Encoding and Decoding
    function HTMLEncode(html) {
        var temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html)
                : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    }
    function HTMLDecode(text) {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }
  • How to get css background picture URL without ('url')

var backgroundImage = $(".home-design1").css('background-image').split("\"")[1];
  • Local Storage Session Storage for HTML5 Tutorials

SessionStorage: 
Save the data in session object. Session is the period of conversation that a user goes through from entering a website to closing the browser when he browses a website. That is to say, the time that a user spends browsing the website is the life cycle of session. The session object can be used to hold any data required to be saved during this period.
This object has two main methods:
Save data: session Storage. setItem (Key, value);
Read data: session Storage. getItem (Key);
Key: The name of the key you want to save. It can be arbitrarily named and understood according to the meaning of the variable.
Value: Represents the value that you want to store in Key, which can be understood by variable assignment.
Usage method:
Save data: session Storage. setItem ("website", "W3Cfuns.com");
Read data: session Storage. getItem ("website");
  • Serialize Json objects into Json strings and submit them for List reception

//HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd"><html><head>
    <title>submitUserList_4</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <script language="JavaScript" src="/js/jquery.min.js" ></script>
    <script type="text/javascript" language="JavaScript">
        //Serialize forms into data in json format (but not for forms with controls, such as check boxes, multiple-choice selections)
        (function($){
            $.fn.serializeJson = function(){
                var jsonData1 = {};
                var serializeArray = this.serializeArray();
                // First convert to {id": ["12","14"],"name": ["aaa","bbb"],"pwd": ["pwd1","pwd2"]} this form
                $(serializeArray).each(function () {
                    if (jsonData1[this.name]) {
                        if ($.isArray(jsonData1[this.name])) {
                            jsonData1[this.name].push(this.value);
                        } else {
                            jsonData1[this.name] = [jsonData1[this.name], this.value];
                        }
                    } else {
                        jsonData1[this.name] = this.value;
                    }
                });
                // Then it's in the form of [{id":"12","name":"aaa","pwd": {pwd1"}, {id":"14","name":"bb","pwd","pwd2"}.
                var vCount = 0;
                // Calculate the maximum length of the array inside json
                for(var item in jsonData1){
                    var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
                    vCount = (tmp > vCount) ? tmp : vCount;
                }

                if(vCount > 1) {
                    var jsonData2 = new Array();
                    for(var i = 0; i < vCount; i++){
                        var jsonObj = {};
                        for(var item in jsonData1) {
                            jsonObj[item] = jsonData1[item][i];
                        }
                        jsonData2.push(jsonObj);
                    }
                    return JSON.stringify(jsonData2);
                }else{
                    return "[" + JSON.stringify(jsonData1) + "]";
                }
            };
        })(jQuery);

        function submitUserList_4() {alert("ok");
            var jsonStr = $("#form1").serializeJson();
            //console.log("jsonStr:\r\n" + jsonStr);
            //alert(jsonStr);
            $.ajax({
                url: "/user/submitUserList_4",
                type: "POST",
                contentType : 'application/json;charset=utf-8', //Setting Request Header Information
                dataType:"json",
                data: jsonStr,
                success: function(data){
                    alert(data);
                },
                error: function(res){
                    alert(res.responseText);
                }
            });
        }
    </script></head>

<body>
    <h1>submitUserList_4</h1>
    <form id="form1">
        ID:<input type="text" name="id"><br/>
        Username:<input type="text" name="name"><br/>
        Password:<input type="text" name="pwd"><br/><br/>

        ID:<input type="text" name="id"><br/>
        Username:<input type="text" name="name"><br/>
        Password:<input type="text" name="pwd"><br/><br/>
        <input type="button" value="submit" onclick="submitUserList_4();">
    </form></body></h

//Java code:
    @RequestMapping(value = "/submitUserList_4", method ={RequestMethod.POST})
    @ResponseBody
    public String submitUserList_4(@RequestBody List<User> users)
            throws Exception{
        String result = "";
        if(users == null || users.size() <= 0){ return "No any ID.Chinese"; }
        result = this.showUserList(users);
        return result;
    }
  • jquery forbids return event response

$(this).keydown( function(e) {
    var key = window.event?e.keyCode:e.which;
    if(key.toString() == "13"){
        return false;
    }
});

  • The redirection uses <c:if test="${message!= null}"></c:if> to prompt error messages.

<c:if test="${message !=null}"><div class = "login-valid">${message }</div></c:if>
  • ajax sends json scrambling code

//HTML
encodeURI($(dom).val(), "UTF-8");    
//JAVA
try{ String decode = URLDecoder.decode(jsonString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
  • Jquery extensions send json

extend(dest,src1,src2,src3...);

Its meaning is to merge src1,src2,src3... into dest, and the return value is the merged dest. It can be seen from this that the structure of DeST is modified after merging this method. If you want to get the result of the merge but don't want to modify the structure of dest, you can use the following:

var newSrc=$.extend({},src1,src2,src3...)// / that is, take "{}" as the dest parameter.

In this way, we can merge src1,src2,src3, and then return the merged results to newSrc. The following examples are given:

var result=$.extend({},{name:"Tom",age:21},{name:"Jerry",sex:"Boy"})
 
So the merged result

result={name:"Jerry",age:21,sex:"Boy"}

That is to say, if the latter parameter has the same name as the former one, the latter one will override the former one.
$.ajax({
                    type: 'POST',
                    url: '<%=basePath%>/getCode',
                      data:$.extend(code1,code2),
                      success:function(data) {
                  
                      },
                      
                  });
  • Asynchronous return of various formats

package com.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

/**
 * Asynchronous return of various formats
 */
public class ResponseUtils {

	//send content  
	public static void render(HttpServletResponse response,String contentType,String text){
		response.setContentType(contentType);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//Sending JSON
	public static void renderJson(HttpServletResponse response,String text){
		render(response, "application/json;charset=UTF-8", text);
	}
	//Send xml
	public static void renderXml(HttpServletResponse response,String text){
		render(response, "text/xml;charset=UTF-8", text);
	}
	//Send text
	public static void renderText(HttpServletResponse response,String text){
		render(response, "text/plain;charset=UTF-8", text);
	}
	
	
}
  @RequestMapping("/demo")
  public void getRoomType(HttpServletResponse response, HttpServletRequest request) {
 
                    JSONObject josnObject = new JSONObject();
                    josnObject.put("code1",code1 );
                    ResponseUtils.renderJson(response, josnObject.toString());
                
                }

Posted by Vebut on Mon, 01 Jul 2019 13:06:09 -0700