Django和Ajax的POST地址有问题

时间:2016-03-24 15:18:00

标签: jquery ajax django post filter

我偶然发现了Django和JQuery / Ajax的一个非常奇怪的问题 网址中有地址:

url(r'^app/insert$', Insert.as_view(), name="insert"),
url(r'^app/insert_ajax$', Insert_Ajax.as_view(), name="insert_ajax"),
url(r'^app/edit/(?P<id>\d+)/$', Edit.as_view(), name="edit"),

如您所见,他们是所有基于对象的视图。还有一个模型:

class TheModel(models.Model):
    item = models.ForeignKey(AnotherModel, related_name="anotherModel")
    attribute = models.ForeignKey(ListOfAttributes, related_name="attributes", blank=True)

和基于给定模型的表格:

class TheModelForm(forms.ModelForm):
    class Meta:
        model = TheModel

所以交易是属性必须根据给定项目改变(过滤)。有一个JQuery处理:

    var change_attribute = function(){

    var selected_item_id = $("#selected_item_id").val();
    $.post("insert_ajax",{"method":"get_attributes","item":$("#id_item").val()}, function( data ) {
        $("#id_attributes").empty();
        $.each(data,function(index, value){
            if(value['id'] == selected_item_id){
                $("#id_attributes").append("<option selected='selected' value='"+ value['id'] +"'>"+value['name']+"</option>");
            }else{
                $("#id_attributes").append("<option value='"+ value['id'] +"'>"+value['name']+"</option>");
            }
        });
    });

}

这直接指向Ajax视图:

class CallDropAjax(View):

    def post(self, request):
        method = request.POST.get('method', None)
        context = {}
        if method:
            try:
                context = getattr(self, method)(request)
            except AttributeError as e:
                context = json.dumps({'success': False,
                                      'error': 'Method %s cannot be called due to %s.' % (method,
                                                                                          str(e))})
        else:
            context = json.dumps({'success': False,
                                  'error': 'No method specified'})

        return HttpResponse(context, content_type="json/application")

    def get_attributes(self, request):
        attributes = ListOfAttributes.objects.filter(
            item__id=request.POST.get('item'))
        json_op = []
        for attribute in attributes:
            json_op.append({"id": attribute.id,
                            "name": attribute.name})
        return json.dumps(json_op)

在插入和编辑视图/表单中使用相同的JQuery脚本,但它仅适用于插入,而不适用于版本。当我查看数据时,插入正确地要求服务器

http://the_server/app/insert_ajax

因此服务器响应,并且相应地过滤和修改属性的下拉列表。但是在版本视图中它不起作用,当我查看ajax询问服务器的内容时​​,它就像这样:

http://the_server/app/edit/2453/insert_ajax

当然是错误的,因此脚本不会收到任何数据,也不会修改任何内容(它只会在下拉列表中留下所有数据)。

所以我的问题是:为什么会发生这种情况,我该如何解决?如何使这个脚本在版本和插入视图中都有效?

2 个答案:

答案 0 :(得分:1)

我假设/app/edit/2453/是可见的网址。

当您从/app/edit/2453/编辑内容时,JQuery会向url + insert_ajax发出一个AJAX POST请求。

见这一行:

$.post("insert_ajax",{"method":"get_attributes","item......

您可以通过将“insert_ajax”替换为编辑页面的完整相对网址(/app/edit/2453/)来修复此行为。

答案 1 :(得分:1)

我解决了!

我必须更改urls.py并添加另一行:

REFERENCES

所以现在可以在编辑中调用脚本,并且它会找到回到相同视图处理程序Insert_Ajax的方式。

此外,我必须修改JQuery脚本,以便它运行BOTH调用 - insert_ajax和insert_insert_ajax:

url(r'^app/insert$', Insert.as_view(), name="insert"),
url(r'^app/insert_ajax$', Insert_Ajax.as_view(), name="insert_ajax"),
url(r'^app/edit/(?P<id>\d+)$', Edit.as_view(), name="edit"),
url(r'^app/edit/insert_ajax$', Insert_Ajax.as_view(), name="insert_insert_ajax"),

并将响应处理程序抛出到另一个函数&#34; change_item&#34; (所以我不必复制+粘贴代码。

它有效!不是一个非常优雅的解决方案,对两个视图的冗余调用一起希望其中一个响应,但现在它会做。当我学习如何检查URL调用是否成功时,我可能会稍后更改它。