0

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!

0

1 Answer 1

1

You're getting your server and client sides mixed up here. The

${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}

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

function goToPage(itemId, val){
  window.location.href="/myapp/GOrder/updateShoppingCart?item=&amp;qty=" + itemId + val;
}

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

function goToPage(itemId, val){
  window.location.href=
     "${createLink(controller:'GOrder', action:'updateShoppingCart'
         ).encodeAsJavaScript()}?item=" + encodeURIComponent(itemId)
    + "&amp;qty=" + encodeURIComponent(val);
}

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 JavaScript encodeURIComponent function - if the value of itemId were "item one", for example, you need to append item%20one to the URL.

Sign up to request clarification or add additional context in comments.

2 Comments

I had just figured out something similar, but good suggestion with the encoding! Thanks!
i wonder a little on the encoded '&' in the url, but otherwise, that's the ticket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.