javascript - 如何将 View 中的多个值导入到模板中的多个按钮中?

标签 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;
        $.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);

如果我在 View 中返回此内容:

return HttpResponse(vr)

但不能同时使用多个。

最佳答案

我假设您在此处返回 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
    })

}

关于javascript - 如何将 View 中的多个值导入到模板中的多个按钮中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61448936/

相关文章:

javascript - jQuery 递增或递减变量 1

javascript - 将参数传递给回调 JavaScript

javascript - 服务器不可用

javascript - Ajax调用相同的id

javascript - 使用单个复选框显示多个密码字段

html - CSS Flex,不限制列表项的顺序

R,utf-8 字符似乎无法滑动

html - 将图像链接居中对齐

jquery - jqgrid json加载行号为负

javascript - 删除 JQuery 1.11.1 事件(对于用户脚本)