通過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模型儲蓄和響應的正確方法,我將不勝感激。
我覺得這個代碼的最後一行必須是: 返回的HttpResponse(「未授權」) – 2011-08-11 22:23:52