Passing parameter map (list of values) to JQuery
to initialize a javascript loaded grid, I need to pass a list of values from controller/gsp. Since the javascript is activated once the page is rendered/loaded, there may not be a direct way to do it. 2 possibilities 1. do an ajax call, and retrieve the list of values from the server 2. store the list in html as a hidden element, and read it from javascript.
option 2 seems better as it avoids few calls back to server. So, which control should I use for开发者_StackOverflow中文版 a list of values? Any jQuery code snippet to read it back into array/list.
thanks in advance.
It depends on the size of that data. It it's small enough, you could embed it in the page. For example, to populate a calendar with events, I used something like:
<div id="calendar" data-events="[/* event list */]"></div>
(the data-events
attribute contained a JavaScript array of event objects in JSON format)
However, if you're talking about a huge amount of data, loading it (possibly in chunks) asynchronously after the page load (or when the document is ready) could increase your app's performace and make it more interactive (i.e. I don't want to wait and load that data if the next thing I'm gonna do is navigate away)
Does that answer your question?
You can directly write JavaScript from the server side. I don't know about grails, but here's a very simple example in php:
<script type="text/javascript">
var someVar = "<?php echo $someServerVar;?>";
</script>
Sure, this example is very simple, but you get the idea. And most languages will have some sort of function that escapes JavaScript strings (basically turn "
into \"
and new lines into \n
).
If you put a script like that at the top of your <head>
, then those variables will be accessible from all other scripts on the page.
精彩评论