Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - D3 is not responding after 2 nd time i hit the database for some result

I am using a D3 api in which i am representing some hierarchy between the nodes through links between them.all the data comes from database when i load the page.But here i have a criteria where i have to filter top 3 or 5 nodes i.e i have a select box here where i have values from 1 to 5.Now if i go for 2 the database will return the hierarchy for 2nd level.But i have a problem here when i load the page ,onload it will return a default level from the database,but when i go for 2nd or 3 rd level the database will generate the required json but this time the api is not populating along with the values,instead it is returning/printing the calculated json in the html page. Here is my code ...

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.node circle {
    cursor: pointer;
    stroke: #3182bd;
    stroke-width: 1.5px;
}

.node text {
    font: 10px sans-serif;
    pointer-events: none;
    text-anchor: middle;
    }

    line.link {
    fill: none;
    stroke: #9ecae1;
    stroke-width: 1.5px;
    }

 </style>
 <body>

  <script type="text/javascript" src="d3/d3.v3.min.js"></script>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

    var width = 1200,
    height = 700,
    root;

    var force = d3.layout.force()
    .linkDistance(80)
    .charge(-120)
    .gravity(.04)
    .size([width, height])
    .on("tick", tick);

    //adding as svg element
    var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

    var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

    d3.json("JsonServlet", function(error, json) {
        root = json;
        update(); //responsible for creating the layout
    });

    function update() {
        var nodes = flatten(root),

        /*
         *d3.layout.tree() is the starting point 
         *for tree layouts in D3. 
         *The call to this function returns an object
         * that contains a bunch of methods to configure 
         * the layout and also provides methods to 
         * compute the layout
         **/           

        links = d3.layout.tree().links(nodes);//attach the nodes

        // Restart the force layout.
        force
        .nodes(nodes)
        .links(links)
        .start();

        // Update links.
        link = link.data(links, function(d) { return d.target.id; });

        link.exit().remove();

        link.enter().insert("line", ".node")
        .attr("class", "link");

        // Update nodes.
        node = node.data(nodes, function(d) { return d.id; });

        node.exit().remove();

        var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .on("click", click)
        .call(force.drag);

        nodeEnter.append("circle")
        .attr("r", function(d) { return Math.sqrt(d.size) / 10 || 4.5; });

        nodeEnter.append("text")
        .attr("dy", ".35em")
        .text(function(d) { return d.name; });

        node.select("circle")
        .style("fill", color);
    }


    /*Giving elements on click*/
    function tick() {
        link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

        node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
    }


    /*Adjusting the color of each node*/
    function color(d) {
        return d._children ? "#3182bd" // collapsed package
        : d.children ? "#c6dbef" // expanded package
        : "#fd8d3c"; // leaf node
    }
   var checkNodes = [];
    // Toggle children on click.
    function click(d) {


       checkNodes.push(d);
        update();
    }

    function collectNames(){
            var res = []
            checkNodes.forEach(function(v){
                res.push(v.name);
            })
            return res;
        }


    function send(){
   var name=d.name;

        $.ajax({
            url: "ActionServlet",
            type: "post",
            //data: [extract each node names from "checkNodes"],
            data:collectNames(),//send name array to server 
            error:function(){
                //alert("error occured!!!");
            },
            success:function(d){
                //alert(d.name);
            }
        });
    checkNodes = [];//clear 
};

    // Returns a list of all nodes under the root.
    function flatten(root) {
        var nodes = [], i = 0;

        function recurse(node) {
            if (node.children) node.children.forEach(recurse);
            if (!node.id) node.id = ++i;
            nodes.push(node);
        }

        recurse(root);
        return nodes;
    }

</script>
  <form method="post" action="JsonServlet">
 <select name="options">
<option>Choose Your Option</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
 </select>
    <input type="submit" value="submit"/>
   </form>       

This is my servlet

public class JsonServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        int option =Integer.parseInt(request.getParameter("options"));
        System.out.println(option);
        List<String> listofParent = new ArrayList<String>();
        List<String> listofChild = new ArrayList<String>();
        DBConn con = new DBConn();
        Connection conn = con.getConnection();
        Statement st = conn.createStatement();
        String sqlQuery = "select * from link_table";
        ResultSet rs = st.executeQuery(sqlQuery);

        while (rs.next()) {

            listofParent.add(rs.getString(1));
            listofChild.add(rs.getString(2));
        }

        Entry mainRoot = null;
        Entry e = new Entry("1008574975");
        Entry e1 = new Entry("987456215");
        for (int i = 0; i < listofParent.size(); i++) {

            Entry root = new Entry(listofParent.get(i));
            mainRoot = aMethod2form(root, listofChild);

            e.add(mainRoot);


        }
        e1.add(e);
        Gson g = new Gson();
        System.out.println(g.toJson(e1));

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(g.toJson(e1));


    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

private Entry aMethod2form(Entry root, List<String> listofChild) {
    for (int i = 0; i < listofChild.size(); i++) {

        root.add(new Entry(listofChild.get(i)));
    }

    return root;
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...