I have ROR Helper that build some Javascript code. In the helper I have Hash of options and variables that define this javascript code. One of them is string that holds JS function, the problem is it rendered as a string and not as function when using to_json.
How can I make it work?
Example:
In my helper I have this code:
h = {url: '/some/url', async: false}
h[success] = "function(result) {alert(result);}"
"<script type='text/javascript'> jQuery.ajax(#{h.to_json}); </script>"html_safe
This code will generates:
<script type='text/javascript'>
jQuery.ajax({
url: '/some/url',
async: false,
success: "function(result) {alert(result);}"
});
</script>
What I wont to to achieve is that code (without the ".." in success part):
<script type='text/javascript'>
jQuery.ajax({
url: '/some/url',
async: false,
success: function(result) {alert(result);}
});
</script>
You could create a string out of h hash instead of using to_json; for example:
def js_code
h = {url: '"/some/url"', async: false}
h[:success] = "function(result) { alert(result); }"
s = h.map { |k, v| "#{k}: #{v}" }.join(",")
"<script type='text/javascript'> jQuery.ajax({#{s}}); </script>".html_safe
end
Notice that additional double quotes (") were added to '"/some/url"' in order to keep them in the final string.
Output:
<script type='text/javascript'> jQuery.ajax({url: "/some/url",async: false, success: function(result) { alert(result); }}); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With