37
18.16 AJAX with jQuery
jQueryisasmallJavaScriptlibrarycommonlyusedtosimplifyworkingwiththeDOM
and JavaScript ingeneral. It is the perfect tool to make web applications more dynamic
by exchanging JSON between server and client.
JSON itself is a very lightweight transport format, very similar to how Python primi-
tives (numbers, strings, dicts and lists) look like which is widely supported and very
easy to parse. It became popular a few years ago and quickly replaced XML as trans-
port format in web applications.
18.16.1 Loading jQuery
In order to use jQuery, you have to download it first and place it in the static folder of
your application and then ensure it’s loaded. Ideally you have a layout template that
is used for all pages where you just have to add a script statement to the bottom of
your <body> to load jQuery:
<script type=text/javascript src="{{
url_for(static, filename=jquery.js) }}"></script>
Another method is using Google’sAJAXLibrariesAPIto load jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write(<script src="{{
url_for(static, filename=jquery.js) }}">\x3C/script>)</script>
In this case you have to put jQuery into your static folder as a fallback, but it will
first try to load it directly from Google. This has the advantage that your website will
probably load faster for users if they went to at least one other website before using
the same jQuery version from Google because it will already be in the browser cache.
18.16.2 Where is My Site?
Do you know where your application is? If you are developing the answer is quite
simple: it’s on localhost port something and directly on the root of that server. But
what if you later decide to move your application to a different location? For example
to http://example.com/myapp? On the server side this never was a problem because
we were using the handy url_for() function that could answer that question for us,
but if we are using jQuery we should not hardcode the path to the application but
make that dynamic, so how can we do that?
Asimple method would be to add a script tag to our page that sets a global variable
to the prefix to the root of the application. Something like this:
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
139