Javascript 如何将视图中的多个值导入模板中的多个按钮?
我在index.html中有一组按钮,在views.py中有一个字典,其中包含一些按钮的值,我通过ajax导入这些按钮。我要做的是浏览字典并将每个值加载到它的特定按钮中 这基本上就是htmlJavascript 如何将视图中的多个值导入模板中的多个按钮?,javascript,html,jquery,ajax,Javascript,Html,Jquery,Ajax,我在index.html中有一组按钮,在views.py中有一个字典,其中包含一些按钮的值,我通过ajax导入这些按钮。我要做的是浏览字典并将每个值加载到它的特定按钮中 这基本上就是html $(document).ready(function(){ $(':button').on('click', function(event){ $('#ID').val(this.id); var tmp = this.id;
$(document).ready(function(){
$(':button').on('click', function(event){
$('#ID').val(this.id);
var tmp = this.id;
$.ajax({
type: $('#klik').attr("method"),
url : $('#klik').attr("action"),
data : $('#klik').serialize(),
success: function(d){
{% for gumb in buttons %}
alert('alo')
$('#' + Gumb.id).val(d);
{% endfor %}
//$('#' + tmp).val(d); // this works only for one button, I tried using for loop for multple
},
error: function(){
alert('Greska')
}
});
});
});
至于views.py,这就是我要返回的内容
def klik(request):
print('Test')
if request.is_ajax() and request.POST:
print(request.POST)
ID = request.POST['ID']
vr = r[ID]
gumbi = []
g = Gumb(ID, vr)
gumbi.append(g)
...something....
d = dict()
d['buttons']= gumbi
#return render(request,'index.html', d)
return HttpResponse(d)
gumbi中可能有更多的Gumb,Gumb是一个类,其中Gumb.id与html中按钮的id相同,Gumb.b是我希望在按钮中使用的值
它只使用一个标记为的按钮:
//$('#' + tmp).val(d);
如果我在视图中返回此选项:
return HttpResponse(vr)
但不是使用multiple。我假设您在这里返回一个JSON对象列表
[{d:data},{d:data}]
//ajax code
success: function(data) {
//use $.each here not the framework each
$.each(data, function(index, value) {
console.log(value) //iterates your data see dev tools console for prints
})
}
您好,Idk关于您使用的框架。但是请确保您正在返回一个JSON对象,我正在查看
returnhttpresponse(obj)代码>我的字典d从以前的代码开始看起来像{'buttons':[(ID:r3s6,Value:0)…]},现在我已经将它重写为例如{'r3s6':0,…}。我还尝试在html代码中将其转换为JSON,比如:var myJSON=JSON.parse(d)
,但我不明白代码中的索引和值是什么,以及如何访问myJSON中的数据。此外,我还尝试在ajax的成功部分添加一些警报,以检查它是否有效,但没有弹出警报。函数(d)中的d都是字典的键粘在一起。。。idkI的意思是,它甚至通过你的控制器吗?只要它可以返回一个json对象数组,比如[{key:value},{key:value}]
,我们就可以解决前端部分的问题。问题是,当我试图将我的列表或字典转换为json对象时,它会变成一个大字符串(例如,“{”r8s8“:0,“r8s7”:1,“r7s8“:1}”),当我试图提醒d[2]时,它会返回“r”。我不知道如何获取任何数据。我无法通过钥匙访问它,也不知道它们是哪一个,因为它们各不相同。