我已经使用localStorage.setItem(" Key",JSON.stringify(obj))将Django表单元素加载到localStorage以持久化更改。这似乎有效。现在我想检索对象并将其从Javascript渲染到我的HTML页面中。我的脚本看起来像这样:
// This script retrieves the Django form object that was stored as a JSON
// from localStorage, parses it and posts it on the html page
// Get label from document
var myLabel = document.getElementById("currLabelID" +
id_suffix).value.replace(/ /g,"");
//alert("CurrLabel = " + myLabel);
// Retrieve the form object from localStorage
var yummy = JSON.parse(localStorage.getItem(myLabel));
// Put form object into page
//var myDiv = document.getElementByName("theFieldPostDiv");
//$( myDiv ).append( yummy );
//var form = document.createElement('form');
//form.appendChild(yummy);
//document.write( yummy );
//{{ yummy }}
//$(document).ready(function() {
//
// $( "theFieldPostDiv" ).append( yummy );
//
//});
//$( "theFieldPostDiv" ).append( $(yummy) );
//document.body.appendChild(yummy);
//$.append(yummy);
//yummy.post();
$(function() {
$(".theFieldPostDiv").hide();
$("#form-group").submit(function(event) {
event.preventDefault();
var posting = $.post(".theFieldPostDiv", yummy);
posting.done(function(data) {
$(".theFieldPostDiv").show();
});
posting.fail(function(data) {
alert("Fail")
});
});
});
注意:" theFieldPostDiv"是我想在页面中呈现表单对象的地方。
注释代码显示了我尝试实现此目的的几种方法。任何帮助表示赞赏。
答案 0 :(得分:0)
所以我找到的解决方案是,在模板的底部添加:
{% block js %}
function loadInputLocalStorage(){
$('#input-form :input').each(function(){
var key = $(this).attr('id');
if(localStorage.getItem(key)) {
var value = localStorage.getItem(key);
$(this).val(value);
}
});
}
loadInputLocalStorage();
function saveInputLocalStorage() {
$('#input-form :input').each(function(){
var id = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(id, value);
});
}
$('#input-form').change(function() {
saveInputLocalStorage();
});
{% endblock %}
在模板的正文中我有:
{% for boundfield in elements %}
<div class="form-group">
<label class="control-label col-sm-5" style="text-align:right;"
for="{{boundfield.id_for_label}}">{{ boundfield.label }}
</label>
<div class="col-sm-7" id="{{boundfield.id_for_label}}"
aria-describedby="{{boundfield.id_for_label}} | addstr:ex">{{ boundfield }}
</div>
</div>
{% if boundfield.help_text %}
<p class="col-sm-offset-5 col-sm-7"> <small style="color: grey">{{ boundfield.help_text|safe }}</small></p>
{% endif %}
{% for error in boundfield.errors %}
<div class="col-sm-offset-2 col-sm-10"><span class="text-danger small">{{ error }}</span></div>
{% endfor %}
{% endfor %}
其中&#39;元素&#39;从视图中传入。
注意:我自己没有想到这一点,我得到了Beheen的大力帮助。希望这有助于下一个人...