开发者

Ajax request to controller

I'm new to Play and try some very simple things with AJAX. Right now I only want to send some data to my controller and send something back. I don't get how I can realize this in Play.

I used to send data with

$.get(url, {data:'input'), function() { do something });

to a standard servlet found at /url. In the servlet I have a simple

out.println("html output")

if I want to print something in my html file. I hope you get the point.

In Play I have a function in my controller (it's nonsense, just a test...)

public static void doIt(String input) {
    String out = input+"_foo";
    render(out);
}

I try to call this function with JQuery/AJAX like this:

$(document).ready(function() {
      // when I click a button ...
      $("#send").click(function(){
            var url = #{jsAction @doIt(':input') /} 开发者_如何转开发    
            $.get(url({input: 'x'}), function() {
                ...
            });
      });
});

This is taken from the tutorial and doesn't work. Can somebody give me an idea how to write the controller and the JS to send some random string to my controller and return something.

Cheers


Try renderText() instead of render():

public static void doIt(String input) {
    String out = input + "_foo";
    renderText(out);
}

And try to explicitly define the controller you use if your view (where you write the script) does not belong to YourController:

$(document).ready(function() {
  // when I click a button ...
  $("#send").click(function(){
        var url = #{jsAction @YourController.doIt(':input') /}     
        $.get(url({input: 'x'}), function() {
            ...
        });
  });

});

It works for me. And important thing: This will only work at view file not separate js


I agree the doc here http://www.playframework.org/documentation/1.1.1/ajax is not exactly clear. It says:"In this example we are requesting the list method from the default Application controller". But generally, you don't call the default Controller but one specific one.
So as Tim said, the best way is to specify the controller in your jsAction:

 #{jsAction @YourController.doIt(':input') /}  

It should work!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜