Call Wicket 6 Code from Javascript and return valu

2019-09-20 05:59发布

I have managed to call my Wicket 6 Java code from Javascript using option A in this example: https://stackoverflow.com/a/42612027/1047418

However, I have not been able to find examples for returning data from the Java side back to JavaScript (the generated JavaScript callback function does not even include a return statement). How can this be achieved?

Edit: I am not trying to set an attribute in Java and as I've already explained, calling Wicket from JavaScript is not the problem here. I am trying to return a JSON object from Wicket back to the browser as a result of an Ajax request.

Edit2: Following martin-g's examples I cobbled up this working example...

Java

public class MyAjaxBehaviour extends AbstractDefaultAjaxBehavior {

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);
        tag.put("aprachatcallbackurl", getCallbackUrl());
    }

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        super.updateAjaxAttributes(attributes);
        attributes.setDataType("json");
        attributes.setWicketAjaxResponse(false);
    }

    @Override
    protected void respond(AjaxRequestTarget target) {
        getComponent().getRequestCycle().replaceAllRequestHandlers(
            new TextRequestHandler("application/json", "UTF-8", "{...JSON GOES HERE...}));
    }
}

JavaScript

var mySuccessCallback = function(param1, param2, data, statusText) {
    // Data contains the parsed JSON object from MyAjaxBehaviour.respond(...)
    ...
}

var myFailureCallback = function() {
    ...
}

Wicket.Ajax.get({
    "u": callbackUrl,
    "dt": "json",
    "wr": false,
    "sh": [mySuccessCallback],
    "fh": [myFailureCallback]
});

Main problem as that the Wicket 7 Reference incorrectly instructs to use "wr" instead of "dt" in the JavaScript call. :)

2条回答
叼着烟拽天下
2楼-- · 2019-09-20 06:19

You can just write a Resource and mount it, and get it with your favorite Ajax-approach.

For example:

public class MyResource extends AbstractResource
    @Override
    protected ResourceResponse newResourceResponse( Attributes attributes )
    {

        ResourceResponse resourceResponse = new ResourceResponse();
        resourceResponse.setContentType( "text/json" );
        resourceResponse.setTextEncoding( "utf-8" );

        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();

        try
        {
            this.json = IOUtils.toString( request.getInputStream() );
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }

        resourceResponse.setWriteCallback( new WriteCallback()
        {
            @Override
            public void writeData( Attributes attributes ) throws IOException
            {
                OutputStream outputStream = attributes.getResponse().getOutputStream();
                Writer writer = new OutputStreamWriter( outputStream );


                writer.write( MyResource.this.json );
                writer.close();
            }
        } );

        return resourceResponse;
    }

(Copied from my other answer here https://stackoverflow.com/a/17876029/461499)

And see here for mounting it: https://dzone.com/articles/how-implement-rss-feeds-custom

查看更多
唯我独甜
3楼-- · 2019-09-20 06:23

I think you can do it in a simpler way!

Wicket Ajax API is just: Wicket.Ajax.ajax({...}). All you need to prepare at the server side is to save the callback url, e.g. by saving it globally in the window object or in HTML element's attributes (data-the-url).

public class CallFromJavascriptBehavior extends AbstractDefaultAjaxBehavior {
   @Override
   protected void respond(AjaxRequestTarget target) {
      final StringValue parameterValue = RequestCycle.get().getRequest().getQueryParameters().getParameterValue("yourName");
      System.out.println(String.format("Hello %s", parameterValue.toString()));

      // write anything to the WebResponse and then consume it in the JS success handler. See below
   }

   @Override
   public void onComponenntTag(ComponenntTag tag, Component component) {
       super.onComponenntTag(tag, component);
       tag.put("data-the-url", getCallbackUrl());
   }
}

Then in your JS code you can do:

var callbackUrl = jQuery("#theElementId").data("the-url");
Wicket.Ajax.get({"u": callbackUrl, "sh":[successHandler], "fh": [failureHandler] });

Where successHandler and failureHandler are JS functions defined inline (e.g. function(...) {}) or elsewhere.

More documentation you can find at: https://ci.apache.org/projects/wicket/guide/7.x/single.html#_ajax_request_attributes_and_call_listeners

A blog article with an complete example at http://wicketinaction.com/2012/07/wicket-6-javascript-improvements/

查看更多
登录 后发表回答