【问题标题】:Django, jquery and $.getDjango、jquery 和 $.get
【发布时间】:2013-08-31 05:22:41
【问题描述】:

是否有 django 函数来检测是否使用 $.get 发送了 ajax 查询?让我解释一下……

我将 Ajax 用于两件事:

1/ 在我的菜单中,我用$.get 显示每个页面的内容(已经实现,在我开始开发第二点之前效果很好)

2/ 在表单内部,当我点击一个按钮时,我使用$.ajax 来显示成功或错误信息(目前正在开发中)

第一点结束,我的观点不变。最后一行:

return render_to_response('auth/index.html', response_dic, context_instance=RequestContext(request))

但是我不得不为第二点改变它:

if request.is_ajax():
    #transform the data to json so it can be used in jquery
    return HttpResponse(simplejson.dumps(response_dic), mimetype='application/json')
#normal post with reload
else:
    return render_to_response('auth/index.html', response_dic, context_instance=RequestContext(request))

但是现在当我点击我的菜单链接时,什么都没有显示了!我想我知道为什么:我用$.get 来表达我的观点。在我看来,request.is_ajax() 返回True,因此它不会按应有的方式渲染视图(它返回HttpResponse 而不是render_to_response)!

所以我重复我的问题:是否有一个函数可以检测 ajax 是否与 GET 一起使用? 如果不清楚,请询问我更多详细信息! 这是我的 jQuery 函数:

//load the content of the page (right side) with Ajax (no need to reload the menu and header)
function load_content(link)
{
    $.get(link, function(data)
    {
        var title=$(data).find("#title");
        var content=$(data).find("#content");
        $("#title_base").html(title);
        $("#content_base").html(content);
    });

    //change the active link in the menu
    $('.active').removeClass('active');
    //~ $(this).addClass("active");
    $('#menu a[href*="' + link.split("/")[2] + '"][class!="noselect"]').parent().addClass('active');
}

想法:我应该使用两种不同的视图吗?

【问题讨论】:

  • request.method == 'GET'?
  • 没错!答案很简单!谢谢。

标签: jquery ajax django request


【解决方案1】:

来自$.get()函数的documentation:“这是一个简写的Ajax函数,相当于:$.ajax(...)”。所以真的没有区别。

如果您希望对它们进行不同的处理,您必须自己创建差异 - 通过调用不同的 URL(视图)或通过传递不同的参数。

【讨论】:

  • 好吧,这是我第一次想到的。但更好更简单:我使用了request.GET
【解决方案2】:

**

解决了!

**

按照 mariodev 的建议,我只需要使用 request.GET。我的看法:

def login_view(request):

    logout(request)
    response_dic={}

    if request.POST:
        #page posted and processed with ajax
        ...
        #transform the data to json so it can be used in jquery
        return HttpResponse(simplejson.dumps(response_dic), mimetype='application/json')


    #displays the page (GET)
    return render_to_response('auth/index.html', response_dic, context_instance=RequestContext(request))

【讨论】:

    猜你喜欢
    • 2012-02-23
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2012-04-16
    • 2018-09-26
    • 1970-01-01
    相关资源
    最近更新 更多