OK, I’m a javascript/grails novice and I’m not sure what to do here.
Basically I have a javascript function that is being called with multiple parameters and I want to substitute them into a grails parsable string.
I have a number of grails drop downs that call a javascript function to link to another page with multiple parameters that need to be passed (item number and quantity).
Here is the select:
<g:select optionKey="key" optionValue="value" value="${item.getQty()}" name="qty" from="[1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9]"
onchange="goToPage('qty${item.id}',this.value)"></g:select>
The javascript function:
<script type="text/javascript">
function goToPage(itemId, val){
window.location.href="${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}" + itemId + val;
}
So, it takes the itemId and val, concats them and replaces the last set of quotes with that concatenated value. What I want to happen is for each of the parameters to replace one of the sets of quotes.
I really don’t understand how what looks like concatenating a string actually substitutes a value.
Thanks!
You’re getting your server and client sides mixed up here. The
is evaluated by Grails on the server side when rendering the GSP into HTML, so what you end up with in your JavaScript will be something like
What you probably want instead is to generate just the base URL up to the question mark on the Grails side, then add the query parameters on the client side in JavaScript
Note the way I’ve added
encodeAsJavaScript()– you should always use this when generating values that are to be included in a JavaScript string literal, it will backslash-escape anything that needs it. Similarly any JavaScript string you’re adding to a URL needs to be encoded using the JavaScriptencodeURIComponentfunction – if the value ofitemIdwere “item one”, for example, you need to appenditem%20oneto the URL.