从Django Ajax函数返回多个变量 [英] Return multiple variables from an django ajax function

查看:154
本文介绍了从Django Ajax函数返回多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Django待办事项列表.将任务标记为已完成的复选框具有ajax:

I'm building a Django todo list. The checkboxes to mark a task as complete have ajax:

//Checkbox toggles
$('input:checkbox').click(function() {
    if ($(this).attr('checked')) {
        $action = true;
    } else {
        $action = false;
    }

    $.ajax({
        type: "POST",
        url: "/gtd/action/" + this.id.split("_")[1] + "/" + $(this).val() + "/" + $action + "/",
        success: function(data) {
            //Update entire gtd side menu
        }
    })
});

在ajax的成功部分中,我需要在侧面菜单中更新多个变量(与未完成任务的数量有关).django视图可以计算变量

In the success portion of the ajax, I need to update multiple variables in a side menu (pertaining to the count of incomplete tasks). The django view can calculate the variables

def ajax_click(request, modelname, id, type, toggle):

    #Do some stuff to save the object

    action_count = actions = Action.objects.filter(complete=False, onhold=False).count()
    hold_count = Action.objects.filter(onhold=True, hold_criteria__isnull=False).count()

    return HttpResponse('')

问题是,如何将多个变量传递回ajax函数?在这种情况下,我有action_count和hold_count.如何将这些变量返回给成功函数?

The question is, how do I pass more than one variable back to the ajax function? In this instance, I have action_count and hold_count. How can I get these variables back to the success function?

推荐答案

最简单的解决方案是从视图中返回一些JSON.类似于以下内容:

The simplest solution is to return some JSON from the view. Something like the following:

import json
data = json.dumps({
        'actions': action_count,
        'holds': hold_count,
    })
return HttpResponse(data, content_type='application/json')

然后,您的客户端代码可以提取所需的信息;因为从外观上看,您使用的是jQuery,它可以通过在传递给 $的对象中设置 dataType:"json" 来自动处理JSON解析以传递给您的成功函数.ajax()调用.

Your client-side code can then pull out the information it needs; since by the look of things you're using jQuery it can handle parsing the JSON for you automatically to pass into your success function by setting dataType: "json" in the object passed to the $.ajax() call.

这篇关于从Django Ajax函数返回多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆