我的视图中有以下代码,它将数据发送到模板,如下所示 -
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
在我的模板中,我可以访问上下文项目 -
@page_template("app/Discover.html")
def Discover(request, template="app/Discover.html", extra_context=None):
context = {}
context['to_loc']=loc_both
context['to_av']=av_both
context['to_ql']=ql_both
if extra_context is not None:
context.update(extra_context)
return render_to_response(template, context, context_instance=RequestContext(request))
这种方式可以从上下文访问单个项目。 但是,我有什么方法可以做如下的事情 -
将上下文对象分配给javascript数组对象,此javascript数组包含上下文对象列表 - &gt;我可以访问如下 -
{% if to_loc %}
js_loc = {{ to_loc|safe }};
{% endif %}
alert('Location is : '+JSON.stringify(js_loc,null,2));
{% if to_av %}
js_av = {{ to_av|safe }};
{% endif %}
alert('AV is : '+JSON.stringify(js_av,null,2));
如何将整个上下文对象分配到js文件中的javascript对象contextJSON中作为数组?
答案 0 :(得分:1)
您可以将您的上下文作为JSON对象放入其中:
@page_template("app/Discover.html")
def Discover(request, template="app/Discover.html", extra_context=None):
context = {}
context['to_loc']=loc_both
context['to_av']=av_both
context['to_ql']=ql_both
if extra_context is not None:
context.update(extra_context)
ctx_copy = context.copy()
context['context_json'] = simplejson.dumps(ctx_copy)
return render_to_response(template, context, context_instance=RequestContext(request))
只需将其作为JavaScript变量呈现在模板中:
jsonList = [];
jsonList = {{ context_json|safe }}; // contextJSON holds the context objects that are sent by my view above
print(JSON.stringify(jsonList.to_loc)); // this should give me the data of locations from respective context object
print(JSON.stringify(jsonList.to_av)); // this is for for AV