简体   繁体   中英

how to pass dictionary object from ajax to controller class in play framework

I have dynatree in my view page, I want to save the current state of the tree on every drag and drop operation, The problem is I am unable to pass that dict object to the controller. The code of ajax is below :

 onDrop: function(node, sourceNode, hitMode, ui, draggable) {
        /** This function MUST be defined to enable dropping of items on
         * the tree.
         */
        logMsg("tree.onDrop(%o, %o, %s)", node, sourceNode, hitMode);
        sourceNode.move(node, hitMode);
        //save state to backend
     var currentTree = $("#tree").dynatree("getTree").toDict();
            $.post("/Application.java", { recieved: currentTree},
               function(data) {
                 $("#output").html(data);
             });


         //expand the drop target
        sourceNode.expand(true);
      },

I have written a method in java that is getting that dictionary object.. But It is giving me error in route file. Error : not found: type Dictionary in this line

POST /hello/:dict controllers.Application.check(dict:Dictionary)

You have many problems in your code.

First, for the main issue, the routes files can not be compiled because it does know your class Dictionary . So you have to tell the file the qualified name of this class (package + class):

POST /hello/:dict controllers.Application.check(dict:package.to.Dictionary)

But AFAIK, it may not work either, because the dynamic part of the Url ( dict ) should be printable in the Url, because, you'll have to call the Url with your dict encoded into it. Let say: /hello/thisIsMyDict

So your best option is to remove the dynamic part of the Url in the routes file:

POST /hello/ controllers.Application.check()

Then, in your action, get the body parameters using a DynamicForm for instance:

public static Result check() {
   DynamicForm myForm = form().bindFromRequest();
   String dict = myForm.get("recieved");
   // convert the string to your Dictionary object
   ...
}

And finally, your javascript code should look like:

var currentTree = $("#tree").dynatree("getTree").toDict();
$.post("@controllers.routes.Application.check()", { recieved: currentTree},
     function(data) {
        $("#output").html(data);
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM