Javascript Ajax和Django—将json对象返回到模板
我试图用Ajax更新我的web应用程序的一部分,但我似乎不知道如何将Json对象传递回模板,因为我要更新的是在页面初始加载时创建的字符数组 Views.pyJavascript Ajax和Django—将json对象返回到模板,javascript,jquery,json,ajax,django,Javascript,Jquery,Json,Ajax,Django,我试图用Ajax更新我的web应用程序的一部分,但我似乎不知道如何将Json对象传递回模板,因为我要更新的是在页面初始加载时创建的字符数组 Views.py def caesarHomePage(request): cipher = alphabet() x = cipher.getListLetter() y = cipher.getListLetter() if request.is_ajax() and request.method == "GET": print("Inside
def caesarHomePage(request):
cipher = alphabet()
x = cipher.getListLetter()
y = cipher.getListLetter()
if request.is_ajax() and request.method == "GET":
print("Inside Request!")
form = caesarCipher(request.GET or None)
if form.is_valid:
print(request.GET.get('the_key'))
integerKey = int(request.GET.get('the_key'))
y = cipher.setCipherLetters(integerKey)
return HttpResponse(json.dumps(y), content_type="application/json")
else:
form = caesarCipher(request.POST or None)
context = { 'x': x,
'y': y,
'form': form,
}
return render(request, 'HomeCaesar.html', context)
Main.js
$("#keyButtonId").on({
click : function() {
var variable = document.getElementById('id_key');
console.log(variable.value)
$.ajax( {
url : "http://127.0.0.1:8000/HomeCaesar/",
type : "GET",
data: { CSRF: 'csrf_token',
the_key: $('#id_key').val()
},
success : function(json) {
// $('#id_key').val('0');
alert(json);
console.log(json);
$('#alteredAlphabet').html(json.y);
console.log("FUNCTION CALLED!");
}
});
}
}))
我要更新的HTML:
<div id="alteredSection">
Altered Alphabet: <br>
{% for y in y %}
<input id="alteredAlphabet" type="text" name="letter{{ y }}" size="1" value = {{ y }}> <br>
{% endfor %}
</div>
更改的字母表:
{y%中y的百分比}
{%endfor%}
使用Ajax时,如何更新HTML中的
y
变量?我是正确返回Ajax还是直接返回模板?json.y是一个数组?你在一个循环中使用“id”(alteredAlphabet),它使多个文本框具有相同的id,id必须是唯一的这是合法的:{%fory y in y%}我设法修复它,不得不将要由Ajax更新的html部分从原始html中取出,并使用{%include“html path”%}在views.py中返回render()使用html文件,该文件包含我想要更新的内容。然后在Ajax函数中,使用$('targeted ID').html(json)PS。现在myy CSS不想更新:我已经有一段时间没碰它了,今天我不得不做一些div的布局,Django不会注意到这些变化。有什么提示吗?json.y是数组吗?你在一个循环中使用“id”(alteredAlphabet),它使多个文本框具有相同的id,id必须是唯一的这是合法的:{%fory y in y%}我设法修复它,不得不将要由Ajax更新的html部分从原始html中取出,并使用{%include“html path”%}在views.py中返回render()使用html文件,该文件包含我想要更新的内容。然后在Ajax函数中,使用$('targeted ID').html(json)PS。现在myy CSS不想更新:我已经有一段时间没碰它了,今天我不得不做一些div的布局,Django不会注意到这些变化。有什么建议吗?