2010-12-16 89 views
1

通過ajax,我想發佈一些數據,如果模型成功得到保存,返回答案作爲JSON對象。基於Django和Ajax的模型保存

這裏是我的jQuery基於Ajax後:

var requestData = { 'ievent_id': type , 'channel_id': CHANNEL_ID , 'start_date': dateToStrConverter(start_date) , 'end_date': dateToStrConverter(end_date) }; 
$.ajax({ 
    type: "POST", 
    url: "my-ajax-url/", 
    data: requestData, 
    dataType: "json", 
    success: function(data){ 
     console.log("ID:" + data.plan_id + " Error:" + data.error); 
    }, 
    error: function(msg){ 
     alert("Theres an error with the server."); 
    }    
}); 

我的Django的視圖處理這一AJAX調用保存iEventPlan對象,並返回響應:

from django.utils import simplejson as json 

def planner_save_view(request): 
    if request.method == "POST" and request.is_ajax(): 
     root = json.loads(request.raw_post_data[0]) 

     ##data 
     ievent = iEvent.objects.get(pk = root['ievent_id']) 
     channel = Channel.objects.get(siservice = root['channel_id']) 
     start_date = datetime.strptime(root['start_date'],'%d-%m-%Y %H:%M') 
     end_date = datetime.strptime(root['end_date'],'%d-%m-%Y %H:%M') 
     response_dict = {} 
     try: 
      plan = iEventPlan(red_button=ievent,channel=channel,start_date=start_date,end_date=end_date) 
      plan.save() 
      response_dict.update({'plan_id': plan.id}) 
     except: 
      response_dict.update({'error': "theres a problem."}) 
     return HttpResponse(json.dumps(response_dict), mimetype="application/json") 
    else: 
     HttpResponse("Not authorized.") 

這是我的錯誤:

JSONDecodeError at /my-ajax-url/ 

No JSON object could be decoded: line 1 column 0 (char 0) 

我在做什麼錯了?如果您向我展示處理基於Ajax的django模型儲蓄和響應的正確方法,我將不勝感激。

+1

我覺得這個代碼的最後一行必須是: 返回的HttpResponse(「未授權」) – 2011-08-11 22:23:52

回答

2

你的標準格式編碼發送POST數據。 dataType屬性沒有指定要發送的數據的類型,但是您期望的可以收到。如果你真的想從您的瀏覽器發送JSON,你應該做這樣的事情:

$.ajax({ 
    data: JSON.stringify(data), 
    processData: false, 
    contentType: 'application/json', 
    // other options 
    } 
1

jQuery的.ajax()函數不會將數據作爲原始JSON發佈。它使用標準的表單編碼格式(dataType參數用於確定預期來自服務器的響應是什麼格式)。

因此而不是json.loads()調用,您應該只是這樣做:

root = request.POST