将 Wicket AbstractAjaxBehavior 与 jQuery.ajax() 结合使用

发布于 2024-10-17 02:35:42 字数 2977 浏览 2 评论 0原文

我已使用 jQuery AJax 调用发送 JSON,如 StackOverflow

问题是我没有在服务器上收到任何数据。我可以看到该调用确实达到了目标 ajax 行为 - 但在 onRequest() 方法中,RequestCycle dd 不包含任何参数

我的 Wicket 代码:

        AbstractAjaxBehavior ajaxSaveBehaviour = new AbstractAjaxBehavior(){
        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        public void onRequest()
        {
            //get parameters
            final RequestCycle requestCycle = RequestCycle.get();



            final PageParameters pageParameters = new PageParameters(requestCycle.getRequest().getParameterMap());
            logger.info(" I have received something 1");

            for(String pkey: requestCycle.getRequest().getParameterMap().keySet()){
                String[] valArry= requestCycle.getRequest().getParameterMap().get(pkey);
                StringBuffer sb = new StringBuffer();
                for(String s: valArry) sb.append(s).append(" , ");
                logger.info("pk :"+ pkey + " = "+ sb.toString());
            }

            //do something using nice json library to produce a string of json

            logger.info(" I have received something 2");
            for(String key: pageParameters.keySet()){
                Object o= pageParameters.get(key);
                logger.info("received key : "+ key + "   = " +o.toString());                    
            }





            String data="ok";        

            requestCycle.setRequestTarget(new StringRequestTarget("application/json", "utf-8", data));
        }


    };
    add(ajaxSaveBehaviour);
    String callBackURL= ajaxSaveBehaviour.getCallbackUrl().toString();

调用此方法的 Javascript

console.log(" call back url :"+ callBackURL);
           $.ajax({
                url: callBackURL,
                type: 'post',
                cache: false,

                data:JSON.stringify(ccbArry[0]),
                contentType: 'application/json',
                dataType: 'json',
                complete: function() {
                        alert(" completed okey dokey!")
                }

            });

从我的 Firebug 控制台,我可以看到 JSON POST已成功创建,并且会触发警报(“完成了,好啊!”)dos。

问题是在 Wicket AbstractAjaxBehavior 上无法在 RequestCycle 中找到任何参数。

我缺少什么吗?有趣的是,我运行 this is debugger asn 时找不到任何参数。这看起来像是编码问题。

从 Firebug 中,我可以看到这是进行的调用,

http://localhost:8080/mywebapp-web-1.0-SNAPSHOT/?wicket:interface=:0::IActivePageBehaviorListener:0:&wicket:ignoreIfNotActive=true&%7B%22type%22%3A9504%2C%22sourceNewsClipBean%22%3A%7B%22type%22%3A9503%2C%22id%22%3A%224cf05752acc1d6aebface86d%22%2C%22typeString%22%3A%22NEWSCLIP_TYPE%22%7D%2C%22startOffset%22%3A%22195%22%2C%22clipDuration%22%3A%22297%22%7D=

不知何故,这些参数不会出现在 RequestCycle 中。这看起来像是一个 encodong 问题。有什么想法吗?

I have used the jQuery AJax call to send JSON as documented here in StackOverflow

The problem is that I am not receiving any Data on the server . I can see that the call did reach the target ajax behavior -- but in onRequest() method , the RequestCycle dd not contain any parameters

My Wicket Code:

        AbstractAjaxBehavior ajaxSaveBehaviour = new AbstractAjaxBehavior(){
        private static final long serialVersionUID = 1L;

        @SuppressWarnings("unchecked")
        public void onRequest()
        {
            //get parameters
            final RequestCycle requestCycle = RequestCycle.get();



            final PageParameters pageParameters = new PageParameters(requestCycle.getRequest().getParameterMap());
            logger.info(" I have received something 1");

            for(String pkey: requestCycle.getRequest().getParameterMap().keySet()){
                String[] valArry= requestCycle.getRequest().getParameterMap().get(pkey);
                StringBuffer sb = new StringBuffer();
                for(String s: valArry) sb.append(s).append(" , ");
                logger.info("pk :"+ pkey + " = "+ sb.toString());
            }

            //do something using nice json library to produce a string of json

            logger.info(" I have received something 2");
            for(String key: pageParameters.keySet()){
                Object o= pageParameters.get(key);
                logger.info("received key : "+ key + "   = " +o.toString());                    
            }





            String data="ok";        

            requestCycle.setRequestTarget(new StringRequestTarget("application/json", "utf-8", data));
        }


    };
    add(ajaxSaveBehaviour);
    String callBackURL= ajaxSaveBehaviour.getCallbackUrl().toString();

My Javascript that invokes this method

console.log(" call back url :"+ callBackURL);
           $.ajax({
                url: callBackURL,
                type: 'post',
                cache: false,

                data:JSON.stringify(ccbArry[0]),
                contentType: 'application/json',
                dataType: 'json',
                complete: function() {
                        alert(" completed okey dokey!")
                }

            });

From my Firebug console, I can see that the JSON POST was made succesfully and the alert(" completed okey dokey!") dos get triggered.

The problem is that on the Wicket AbstractAjaxBehavior is unable to find any parameters in the RequestCycle.

Is there something I am missing ? The funny thing is that I ran this is debugger asn I could not find any parameter. This looks like an encoding issue.

From Firebug, I could see that this was the call that was made

http://localhost:8080/mywebapp-web-1.0-SNAPSHOT/?wicket:interface=:0::IActivePageBehaviorListener:0:&wicket:ignoreIfNotActive=true&%7B%22type%22%3A9504%2C%22sourceNewsClipBean%22%3A%7B%22type%22%3A9503%2C%22id%22%3A%224cf05752acc1d6aebface86d%22%2C%22typeString%22%3A%22NEWSCLIP_TYPE%22%7D%2C%22startOffset%22%3A%22195%22%2C%22clipDuration%22%3A%22297%22%7D=

Somehow , these parameters do not apperd in the RequestCycle. It looks like an encodong issue . Any ideas ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终难愈 2024-10-24 02:35:42

好的,我找到了解决方案:关键是不要使用 requestCycle.getRequest().getParameterMap() 从浏览器读取 JSON。相反,直接从 servlet 输入流读取数据,如下所示:
有用 。

            public void onRequest()
        {
            //get parameters
            final RequestCycle requestCycle = RequestCycle.get();


            WebRequest wr=(WebRequest)requestCycle.getRequest();

            HttpServletRequest hsr= wr.getHttpServletRequest() ;

            try {
                BufferedReader br = hsr.getReader();

                       String  jsonString = br.readLine();
                       if((jsonString==null) || jsonString.isEmpty()){
                           logger.error(" no json found");
                       }
                       else {
                           logger.info(" json  is :"+ jsonString);
                       }



            } catch (IOException ex) {
                logger.error(ex);
            }


            // json string to retir to the jQuery onSuccess function
            String data=getReturnJSONValue();

            logger.info("returning json :"+ data);
            IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", data);
            getRequestCycle().setRequestTarget(t);


            //requestCycle.setRequestTarget(new StringRequestTarget("application/json", "utf-8", data));
        }

ok I found the solution : The keys was to not use requestCycle.getRequest().getParameterMap() to read the JSON from the browser. Instead read the data directly from the servlet input stream as below:
It works .

            public void onRequest()
        {
            //get parameters
            final RequestCycle requestCycle = RequestCycle.get();


            WebRequest wr=(WebRequest)requestCycle.getRequest();

            HttpServletRequest hsr= wr.getHttpServletRequest() ;

            try {
                BufferedReader br = hsr.getReader();

                       String  jsonString = br.readLine();
                       if((jsonString==null) || jsonString.isEmpty()){
                           logger.error(" no json found");
                       }
                       else {
                           logger.info(" json  is :"+ jsonString);
                       }



            } catch (IOException ex) {
                logger.error(ex);
            }


            // json string to retir to the jQuery onSuccess function
            String data=getReturnJSONValue();

            logger.info("returning json :"+ data);
            IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", data);
            getRequestCycle().setRequestTarget(t);


            //requestCycle.setRequestTarget(new StringRequestTarget("application/json", "utf-8", data));
        }
箜明 2024-10-24 02:35:42

wicket 6 和(也许在 wicket 5 中,如果您使用 wicketAjaxPost 而不是 Wicket.Ajax.Post)中的另一个可能的解决方案是使用 Wicket Ajax 浏览器 javascript 库,这样您就可以使用标准 requestCycle.getRequest().getParameterMap( ) 呼唤你的行为。

您可以在这里找到相关信息:

https://cwiki.apache.org/confluence /display/WICKET/Wicket+Ajax

例如,

console.log(" call back url :"+ callBackURL);
           $.ajax({
                url: callBackURL,
                type: 'post',
                cache: false,

                data:JSON.stringify(ccbArry[0]),
                contentType: 'application/json',
                dataType: 'json',
                complete: function() {
                        alert(" completed okey dokey!")
                }

            });

您可以使用:

   var success = function() {alert('success!!!')};
   var failure = function() {alert('failure:-(')};
   // ${callbackUrl} is put in through interpolation in the renderHead of the AbstractAjaxBehavior
   //  TextTemplate interpolater = new PackageTextTemplate(ContentTools.class, "PackageInit.js");

  // Map<String, String> variables = new HashMap<String, String>();
  // variables.put("callbackUrl", getCallbackUrl());
  // interpolater.interpolate(variables);

   var callbackUrl =   '${callbackUrl}';
   var dataMap = {'name' : 'Mr Blogs', 'description' : 'a long description'};
   Wicket.Ajax.post({'u': callbackUrl,
      'ep': dataMap, 
      'sh': [success],
      'fh': [failure]
   });

Another possible solution in wicket 6 and (maybe in wicket 5 if you use wicketAjaxPost instead of Wicket.Ajax.Post), would be to use the Wicket Ajax browser javascript library that way you can use the standard requestCycle.getRequest().getParameterMap() calls in your behavior.

You can find information about this here:

https://cwiki.apache.org/confluence/display/WICKET/Wicket+Ajax

For example instead of:

console.log(" call back url :"+ callBackURL);
           $.ajax({
                url: callBackURL,
                type: 'post',
                cache: false,

                data:JSON.stringify(ccbArry[0]),
                contentType: 'application/json',
                dataType: 'json',
                complete: function() {
                        alert(" completed okey dokey!")
                }

            });

You could use:

   var success = function() {alert('success!!!')};
   var failure = function() {alert('failure:-(')};
   // ${callbackUrl} is put in through interpolation in the renderHead of the AbstractAjaxBehavior
   //  TextTemplate interpolater = new PackageTextTemplate(ContentTools.class, "PackageInit.js");

  // Map<String, String> variables = new HashMap<String, String>();
  // variables.put("callbackUrl", getCallbackUrl());
  // interpolater.interpolate(variables);

   var callbackUrl =   '${callbackUrl}';
   var dataMap = {'name' : 'Mr Blogs', 'description' : 'a long description'};
   Wicket.Ajax.post({'u': callbackUrl,
      'ep': dataMap, 
      'sh': [success],
      'fh': [failure]
   });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文