How to catch AJAX beforeSend event in GWT RPC

229 views Asked by At

Consider the following example with ajax pattern

$.ajax({
        url: "someUrl",          
        beforeSend: function(){
           executeBeforeSend();
        },
        error: function(){
         //some error
        },
         success: function(){
         //some success function
        }
    });

If we there is beforeSend whick executes just before the server call.

Now we all know that GWT RPC use Ajax to server asynchronous calls.

private class MessageCallBack implements AsyncCallback<Message> {
      @Override
      public void onFailure(Throwable caught) {
         /* server side error occured */

      }
      @Override
      public void onSuccess(Message result) {
          /* server returned result, show user the message */
      }    
   }

But ,there is no method like onBeforeSend etc.. How to catch that event?

Is there any workaround ?

2

There are 2 answers

1
Thomas Broyer On

You can use an RpcRequestBuilder that returns a subclass of RequestBuilder where you've overridden the send() methods.

1
Phil On

You can use the javaQuery library to handle this. javaQuery is a partial port of jQuery to Java, and as such has all of the expected Ajax methods:

$.ajax(new AjaxOptions().url("someUrl").dataType("json").type("GET")//get and json are default anyway
                        .beforeSend(new Function() {
                            @Override
                            public void invoke($ javaQuery, Object... params) {
                                executeBeforeSend();
                            }
                        })
                        .error(new Function() {
                            @Override
                            public void invoke($ javaQuery, Object... params) {
                                AjaxError error = (AjaxError) params[0];
                                Log.err("Error %d: %s", error.status, error.reason);
                            }
                        })
                        .success(new Function() {
                            @Override
                            public void invoke($ javaQuery, Object... params) {
                                if (params[0] instanceof JSONObject) {
                                    JSONObject obj = (JSONObject) params[0];
                                    //TODO
                                }
                                else {
                                    JSONArray array = (JSONArray) params[0];
                                    //TODO
                                }
                            }
                        })
                        .complete(new Function() {
                            @Override
                            public void invoke($ javaQuery, Object... params) {
                                executeComplete();
                            }
                        }));