这就是我在 Python Django 框架中使用 JQuery 设置 RequireJS 的方式。在基础顶级 baset_site.html 我在“head”标签之间有以下 require.js 配置代码:
<script>
requirejs.config({
baseUrl: "{% static '' %}",
paths: {
jquery: './js/jslibs/jquery-1.9.1',
jqm: './js/jslibs/jquery.mobile-1.4.0',
ajax_redirect: './js/ajax_redirect',
make_filt_sel: './app_namespace/js/make_filt_sel'
},
shim: {
"jquery": {
exports: '$',
},
"jqm": {
deps: ['jquery'],
exports: '$.mobile'
},
"make_filt_sel": {
deps: ['jquery', 'jqm'],
exports: 'make_filt_sel'
}
}
});
</script>
{% block header_scripts %}{% endblock header_scripts %}
这是我的 ajax_redirect.js
/*
JQuery Ajax typically does not redirect in Django. Need middleware to
setup "class AjaxRedirect(object):" to fix redirection.
Reference:
http://hunterford.me/how-to-handle-http-redirects-with-jquery-and-django/
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ['jquery'], function () {
factory();
});
} else {
// Browser globals
factory();
}
}( this, document, function ( ) {
$(document).ajaxComplete(function(e, xhr, settings){
if (xhr.status == 278){
window.location.href =
xhr.getResponseHeader("Location")
.replace(/\?.*$/, "?next="+window.location.pathname);
}
});
}));
然后我通常在继承的模板中设置“block header_scripts”,如下所示:
{% block header_scripts %}
{{ block.super }}
<script>
if ( typeof define === "function" && define.amd ) {
// AMD {# Configure requirejs.config in base_site.html #}
require(["./app_namespace/js/module_namespace/js_module"]);
} else {
// No AMD
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/make_filt_sel.js" %}",
data:null,
dataType:'script'
});
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/module_namespace/js_module.js" %}",
data:null,
dataType:'script'
});
}
</script>
{% endblock header_scripts %}
这是一个使用依赖项设置 js_module.js 的示例:
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ['jquery', 'jqm', 'ajax_redirect', 'make_filt_sel'], function () {
factory();
});
} else {
// Browser globals
factory();
}
}( this, document, function ( ) {
// A bunch of code
$.mobile.document.on( "pagebeforecreate", function(e){
// a bunch of code
// Shorthand for $( document ).ready()
$(function(){
// a bunch of code
}); // end of $( document ).ready()
}); // end of $(document).on( "pagebeforecreate",
})); // end of (function ( root, doc, factory )