【发布时间】:2016-07-12 06:03:00
【问题描述】:
我偶然发现了 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
这当然是错误的,因此脚本不会接收任何数据,也不会修改任何内容(它只是将所有数据留在下拉列表中)。
所以我的问题是:为什么会发生这种情况,我该如何解决?如何使此脚本在版本视图和插入视图中都有效?
【问题讨论】:
标签: jquery ajax django post filter