We are trying to continually improve our source code base and a question came up recently which throws open a new area to improvement. Where best to put URLs that are needed in JavaScript?
- Do we put the URLs in the JavaScript files themselves?
function onButtonClick() { $.ajax({url:"/my/url/directly/in/the/javascript"}); }
Note: The magic string above is incidental. There could be an object that returns URLs or whatever. The point is that the URLs are stored in the JavaScript files.
- Do we have some mechanism to inject the URLs into the JavaScript. e.g. Having a small script on the page that sets up the URLs from which the JavaScript in the files can access.
<script> var ps = new pageScript(); ps.initUrls({someUrl:<%= Url.Action("SomeAction", "SomeController").ToJson() %>); ps.run(); </script>
The .ToJson()
method is an extension method that turns an object into its JSON serialised version, so, for a string it outputs the quotation marks and escapes it if need be.
Then in the JavaScript file it can pick up the URLs from where ever the initUrls() function stored them.
function onButtonClick() { $.ajax(myUrls.someUrl); }
- Or something else?
We already use 1 and 2 in our code base from various developers over the years, but is there a better way? Or is either of the above a good overall solution?
[action]
attribute of a<form>
.