繁体   English   中英

如何从 Ajax 或 JavaScript 调用 Struts1 Action?

[英]How to call Struts1 Action from Ajax or JavaScript?

我需要在加载 JSP 时调用一个操作。 跟踪访问该页面的用户数量。

我有一个动作VisitorCounterAction ,它会更新数据库。 在加载 JSP 时,我正在调用 ajax 函数callCounter()

{

        alert("callCounter");
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        // i need some correction here
        xmlhttp.open("GET",VisitorCounterAction,false);
        xmlhttp.send(null);
        alert("callCounter returned from Action");
        }

我遇到了一个例外:

/web/guest/content?p_p_id=31&p_p_lifecycle=0&p_p_state=pop_up&p_p_mode=view&_31_struts_action=%2Fimage_gallery%2Fview_slide_show&_31_folderId=10605 generates exception: null

请帮我解决一下这个。 或任何其他方式来调用动作。 我无法重新加载页面,因为它会再次调用 onload 函数。

谢谢,DJ

您需要在调用操作时指定正确的 url。 在您的 struts.xml 文件中,您将创建一个带有名称的操作条目。 假设名称是 VisitorCounterAction。 请注意,这不是 Action 类的名称,而是您在 struts.xml 中使用的名称。

此外,您还需要配置 struts 来识别特定的扩展。 默认情况下它是 .do。

要请求该操作,您将使用:VisitorCounterAction.do。

所以试试:

  xmlhttp.open("GET","VisitorCounterAction.do",false);

还要注意 URL 周围的双引号,因为这是 xmlHttp 对象的 open() 方法中的字符串。

XMLHttpRequest 对象的open方法的第二个参数应该是一个字符串,它是请求的 URL。 在您的情况下,应该是 Struts 的 Action Mapping 映射到您的VisitorCounterAction 就像是:

xmlhttp.open("GET", "/viewCounterAction.do", false); 

如果您使用的是 Liferay 4.2,那么此链接可能会对您有所帮助( http://www.liferay.com/web/guest/community/wiki/-/wiki/Main/Ajax+Toolkit )。 Liferay 4.2 有自己的一组用于执行 AJAX 功能的 javascript API(在 jquery 中实现)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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