我在使用Django和JQuery/Ajax的一个非常奇特的问题绊倒 有地址的网址:Django和Ajax的麻烦POST地址
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>");
}
});
});
}
而这直接转到阿贾克斯的看法:
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
这是当然的,错误的,因此该脚本将不接收任何数据并且不会修改任何内容(它只是将所有数据保留在下拉列表中)。
所以我的问题是:为什么会发生这种情况,我该如何解决它?我怎样才能让这个脚本在编辑和插入视图中工作?
这就是我的想法,但在这种情况下,插入时ajax的完整地址应该是/ app/insert/insert_ajax,但情况并非如此 - 它是/ app/insert_ajax,所以它令我感到困惑为什么它会在insert_ajax附加版本结束。 我提到过,所有视图都在同一个文件中吗?它会改变什么吗? 此外,我试图给一个完整的应用程序的网址,而不是只是Django的名称,但它只是将整个地址追加到版本的URL ... –
这是因为不像编辑网址,其他网址_DO NOT_以'/' 。当网址不以正斜杠结尾时,当前页面(url的最后一部分)被'insert_ajax'替代。避免混合正斜杠url结尾。 – v1k45
我想这是有道理的。但是存在这样的问题,即该数字实际上是来自数据库的项目的ID号码。现在我正在考虑如何解决这个问题,因为第一次启动是使用get方法,所以数据必须以某种方式发送/处理/显示。 –