简体   繁体   中英

How to call Struts1 Action from Ajax or JavaScript?

I need to call an action on load of a JSP. To keep track of number of users who visited that page.

I have an action VisitorCounterAction , where it updates the database. On load of the JSP I'm calling an ajax function 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");
        }

I am getting an exception as:

/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

Please help me with this. Or any other way to call the Action. I can't reload the page as it'll call onload function again.

Thanks, Dj

You need to specify the correct url when calling the action. In your struts.xml file you would have created an action entry with a name. Let's say that name is VisitorCounterAction. Note that this is not the name of the Action class but the name you use in struts.xml.

Also you would have configured struts to recognize a particular extension. By default it is .do.

To request the action you will then use: VisitorCounterAction.do.

So try:

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

Note also the double quotes around the URL as this is a String in the xmlHttp object's open() method.

The second parameter to the XMLHttpRequest object's open method should be a string that is the URL of the request. In your case it should be the Struts' Action Mapping that maps to your VisitorCounterAction . Something like:

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

If you are using Liferay 4.2, then this link might help you ( http://www.liferay.com/web/guest/community/wiki/-/wiki/Main/Ajax+Toolkit ). Liferay 4.2 have own set of javascript API for doing AJAX functionality(Implemented in jquery).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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