我在使用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方法,所以數據必須以某種方式發送/處理/顯示。 –