diff options
author | Aaron LI <aaronly.me@outlook.com> | 2016-11-16 17:44:41 +0800 |
---|---|---|
committer | Aaron LI <aaronly.me@outlook.com> | 2016-11-16 17:44:41 +0800 |
commit | 75d6c2bf1374033ee6ae94c3d17765f72002e935 (patch) | |
tree | 7cc2ffe693817acf7d8bd3f08c62389204ffebfc /fg21sim | |
parent | b32106dbe5008b9125d4a31fa87bb155358b03b7 (diff) | |
download | fg21sim-75d6c2bf1374033ee6ae94c3d17765f72002e935.tar.bz2 |
webui: main.js: Add "getCookie()" and "jQuery.postJSON()" functions
* Add function "getCookie()": get the value of the specified key from
the cookies;
* Add jQuery extension ".postJSON()": wrapper for easier AJAX post,
with the XSRF header and correct content type;
* Also set the default "error" handle function for AJAX request.
Diffstat (limited to 'fg21sim')
-rw-r--r-- | fg21sim/webui/static/js/main.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/fg21sim/webui/static/js/main.js b/fg21sim/webui/static/js/main.js index 3e10fa3..25bc12d 100644 --- a/fg21sim/webui/static/js/main.js +++ b/fg21sim/webui/static/js/main.js @@ -9,6 +9,62 @@ /** + * jQuery settings + */ +jQuery.ajaxSetup({ + error: function (error) { + console.error("AJAX request failed: code:", error.status, + ", reason:", error.statusText); } +}); + + +/** + * Common functions that will be used by other scripts + */ + +/** + * Get the value of a key stored in the cookie + * + * @param {String} name - Name of the key + * + * @return {String} - The value of the key; `undefined` if the key not exists + * + * Credit: + * http://www.tornadoweb.org/en/stable/guide/security.html + */ +var getCookie = function (name) { + var m = document.cookie.match("\\b" + name + "=([^;]*)\\b"); + return m ? m[1] : undefined; +}; + +/** + * jQuery extension for easier AJAX JSON post + * + * NOTE: The XSRF token is extracted from the cookie and posted together. + * + * @param {String} url - The URL that handles the AJAX requests + * @param {Object} data - Data of key-value pairs to be posted + * @param {Function} callback - Function to be called when AJAX succeeded + */ +jQuery.postJSON = function (url, data, callback) { + return jQuery.ajax({ + url: url, + type: "POST", + contentType: "application/json; charset=utf-8", + // Tornado: `check_xsrf_cookie()` + // Credit: https://stackoverflow.com/a/28924601/4856091 + headers: {"X-XSRFToken": getCookie("_xsrf")}, + data: JSON.stringify(data), + success: function (response) { + if (callback) { + callback(response); + } + } + }); +}; + + +/** * Scroll the page to adjust for the fixed navigation banner */ var scrollTarget = function (height) { |