2012-10-12 22 views
1

我有一個表單在用戶跳出「地址」字段後觸發對視圖的ajax請求。它檢索郵政編碼,然後用相同的郵政編碼填充郵政編碼。問題是,如果有任何表單錯誤,那麼下拉的結果是我從get_pickups視圖中生成的結果丟失。我怎樣才能保持它,這樣即使是在形式的錯誤將通過jQuery在窗體錯誤上返回ajax選擇字段

def get_pickups(request): 

    if request.is_ajax(): 
     # Get available pickup dates based upon zip code 
     zip = request.POST.get('zip',None) 
     routes = Route.objects.filter(zip=zip).values_list('route',flat=True)  

     two_days_from_today = date.today() + relativedelta(days = +2) 

     submitted_from = request.POST.get('template',None) 
     if submitted_from == '/donate/': 
      template = 'donate_form.html' 
      results = PickupSchedule.objects.filter(route__in=routes,date__gt = two_days_from_today, current_count__lt=F('specials')).order_by('route','date') 
     else: 
      template = 'donate-external.html' 
      results = PickupSchedule.objects.filter(route__in=routes,date__gt = two_days_from_today, current_count__lt=F('specials')).order_by('date')   

     return render_to_response(template,{ 'zip':zip, 'results':results}, context_instance=RequestContext(request)) 

我的Ajax調用保存的結果:

$.ajax({ 
     type: "POST", 
     url:"/get_pickups/", 
     data: { 
     'zip': zip, 
     'template':template 
     }, 
     success: function(data){    

       results = $(data).find('#results').html()   
       $("#id_pickup_date").replaceWith("<span>" + results + "</span >");  
     }, 
     error: function(){ 
      alert("Error"); 
     } 
+0

你能舉一個「表單錯誤」的例子嗎?例如壞的郵編? – Jeff

+0

這不一定是郵政編碼的錯誤,但是如果表單上有任何其他錯誤(如未輸入必填字段)。 – Austin

回答

1

我能想到的兩種方法:

  1. 附加如果出現錯誤(下降:服務器代碼中增加了複雜性),則將該下拉內容返回到POST並將其與其他字段中的數據一起返回。
  2. 使用javascript在頁面加載/重新加載時檢查該zip字段是否非空。如果它不是空的(如錯誤返回),請致電AJAX查找該下拉菜單(下行:重複計算)

我想使用的任何解決方案,您覺得最熟練(蟒蛇/ Django的或JavaScript)

+1

提交我的問題後,我意識到我可以用你在解決方案2中提到的相同方式來做到這一點。我寧願在python/django中執行此操作,但是如果字段長度大於零,然後使得相同的ajax呼叫。謝謝 – Austin