ajax json array and background using transmission array ------ distal json json station transmits back to the front end of the array

 

1. primer

        Json cross-language intermediate language data exchange, data that represents a way of key / value pairs, such simple data types that can be understood by most programming languages. It therefore is the main mode and basic data of the front and rear ends of the exchange.

2. The front end next station data transmission json

        The first step should be to define a JSON object or JSON array. json object is the "var jsonObj = {" name1 ":" value1 "," name2 ":" value2 "," name3 ":" value3 ", ...};" to define the format, and the array is based json brackets "[ ] "package format defines a plurality json objects, such as" var jsonArray = [{ 'name1': 'value1', 'name2': 'value2', ...}, { '_name1': '_value1', '_name2': '_value2', ...}, ...] ".

< Script type = "text / JavaScript" > 
    <! - definition of JSON array -> 
    var jsonStr = [{
         " the empNo " : " 1242 " ,
         " DEPTNAME " : " Sales " ,
         " password " : " 24284 " ,
         " hobbys " : " dancing the Internet " ,
         " empName ": " Xiao Wu",
        "sex" : "",
        "infor" : "好学生"
    }, {
        "empNo" : "1254",
        "deptName" : "技术部",
        "password" : "24224",
        "hobbys" : "跳舞  唱歌",
        "empName" : " Xiao Ming " ,
         " Sex " : " female " ,
         " Infor " : " a beautiful girl " 
    }]; 


</ Script >

 

        The second step is defined ajax method. ajax data parameter to be noted that the wording of the method, the method can not be directly provided on the key, use braces {} wrapped up key / value pairs define, and treated with the JSON.stringify () will be converted to an object method json character string form . If no ** JSON.stringify () ** method, the background can not be obtained json java code objects.

< A the href = "JavaScript: sendJson ()" > send data Json </ A > 

< Script type = "text / JavaScript" > 
    <! - send data to the servlet processing json -> 
    function sendJson () { 
        $ .ajax ({ 
            of the type: " POST " , 
            url: " HTTP: // localhost:? 8080 / jspdemo / the servlet / EmployeeServlet Action = getJsonObj " , 
            the Data: { 
                ' jsonObj ' : JSON.stringify (jsonStr) // original json objects into String 
            }, 
            Success: function (MSG, Status) { 
                Alert ( " the request was submitted in response to successfully " ); 
            } 
        }); 
    } 
    </ Script >

 

        The method defined in servlet class, with Ali Baba fastjson kit JSONArray.parseArray (String text, Class clazz) method, the string of key-value pairs arranged in a manner to parse json array java array object.

   public void getJsonObj(HttpServletRequest request, HttpServletResponse response)
    {
        String empStr = request.getParameter("jsonObj");
        System.out.println("empjson字符串" + empStr);
       List< Employee> emps = JSONArray.parseArray(empStr,Employee.class);
       System.out.println("json传到后台的Employee数据:" );
       for(Employee emp: emps){
          System.out.println(emp);
           
       }
    }

 

  

                Console output
Here Insert Picture Description

3. Background to the tip of the transmission data json

        A first step, the method defined in servlet using Alibaba fastjson kit JSONArray.toJSON (Object javaObject) java object into the data format json string. String () method sends this to the front end with a print PrintWriter

  public void getEmpList(HttpServletRequest request, HttpServletResponse response)
    {
        List<Employee> empList = generateEmployeeList();
        for(Employee emp: empList){
            System.out.println(emp);
         }
        try
        {
            //转为json数据形式的字符串
response.getWriter().print(JSONArray.toJSON(empList).toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

 

        The second step, the corresponding background servlet request method using ajax method. The optional parameters set ajax "dataType" should be set to "json", such a return explicitly declare data type is json format, wherein the elements can be removed directly by their subscripts. If omitted, "dataType" default "text", it is necessary to ( "(" + data + ")") which was transformed with the function eval json format is then recycled through the elements of the array json therein.

< Script type = "text / JavaScript" > 
<-! Ajax show all methods -> 
    function ajaxQueryAll () { 
        $ .ajax ({ 
            type: " the POST " , 
            URL: " HTTP: // localhost: 8080 / jspdemo / ? the servlet / EmployeeServlet Action = getEmpList " ,
             / * dataType parameter if not written, need to use the function" var $ result = eval ( ' (' + data + ')'); " into json format, 
            then traverse $ result in element * / 
            dataType: " json " , 
            Success:function (data) {
                 were $tbody = $("#table-main");
                var $data = $(data);
                /* 以下标遍历 */
                    /* for (var i = 0; i < data.length; i++) {
                        $tbody.append("<tr >");
                        $tbody.append("<td>" + data[i].empNo + "</td>");
                        $tbody.append("<td>" + data[i].empName + "</td>");
                        $tbody.append("<td>" + data[i].sex + "</td>");
                        $tbody.append("<td>" + data[i].deptName + "</td>");
                        $tbody.append("<td>" + data[i].hobbys + "</td>");
                        $tbody.append("<td>" + data[i].infor + "</td>");
                        $tbody.append("</tr >");
                    }
                     */
        /*forEach循环遍历  */
                $data.each(
                    function() {
                        $tbody.append("<tr >");
                        $tbody.append("<td>" + this.empNo + "</td>");
                        $tbody.append("<td>" + this.empName + "</td>");
                        $tbody.append("<td>" + this.sex + "</td>");
                        $tbody.append("<td>" + this.deptName + "</td>");
                        $tbody.append("<td>" + this.hobbys + "</td>");
                        $tbody.append("<td>" + this.infor + "</td>");
                        $tbody.append("</tr >");
                    }
                );
            }
        });
    }
    </script>
    
    <input type="button" onClick="ajaxQueryAll()" value="ajax查询所有" />
    <table width="400px" align="center" border="1px"
        style="background-color:orange;">
        <thead>
            <TR > 
                < TH> employee number </ TH > 
                < TH > Name </ TH > 
                < TH > gender </ TH > 
                < TH > sector </ TH > 
                < TH > Hobbies </ TH > 
                < TH > Additional information </ TH > 
            </ TR > 
        </ thead > 
        < tbody ID = "Table-main" > 
        </tbody>
     </table>

 

                Console output
Here Insert Picture Description
                front page display

 

 

Guess you like

Origin www.cnblogs.com/gocode/p/11111963.html