brajnandan
brajnandan

Reputation: 21

How can I assign dynamic value to the parameter of a URL within JavaScript using struts2 framework?

On the onchange event on the dropdown list I called a JavaScript method. In this JavaScript method, I called an action class using URL tag and this URL also carries value through a parameter. But when I am doing this, I always get a null value for the setter/getter
method of the action class.

My code is: calling setbusiness() method inside javascript from onchange event of dropdown list and also passing value to it. Alert messages come with id value. But when xmlhttp.open("GET",url,true) called then action class is called with setter method with null value. I don't understand why the value is not coming. Please help me how can I assign dynamic value to the parameter of URL.

<script>  
function setbusiness(sourceid) {  
alert(" sourceid "+sourceid);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
}
}
var url = "<c:url action="feedajax.action">
<c:param name="sourceid">"%{sid}"</c:param></c:url>";                
xmlhttp.open("GET",url,true);
xmlhttp.send();
} 
</script>    

    

Upvotes: 1

Views: 3333

Answers (1)

Dave Newton
Dave Newton

Reputation: 160301

var url = "<c:url action="feedajax.action"><c:param name="sourceid">"%{sid}"</c:param></c:url>";                

You're using an OGNL escape in the middle of a JSP. JSP knows nothing about OGNL. You're also trying to concatenate two strings without a + so the syntax would fail anyway.

You may use normal JSP EL because of S2's request wrapper:

var url = "<c:url action="feedajax.action"><c:param name="sourceid">${sid}</c:param></c:url>";                

OGNL expressions are only valid inside something that knows about OGNL, like S2 tags.

While it's not the problem, IMO using the same quotes for both your JS string and JSTL parameters makes reading the source very difficult–IMO it's cleaner to distinquish between the two:

var url = '<c:url action="feedajax.action"><c:param name="sourceid">${sid}</c:param></c:url>';

Even better, don't conflate the two operations, and use <c:param>'s value attribute:

<c:url var="feedUrl" action="feedajax.action">
  <c:param name="sourceid" value="${sid}"/>
</c:url>

var url = '${feedUrl}';

Caveat If the source ID is something that can be passed in by a user, it should be JS-escaped.

Upvotes: 1

Related Questions