【问题标题】:Django and Ajax based model saving基于 Django 和 Ajax 的模型保存
【发布时间】:2010-12-16 09:41:40
【问题描述】:

通过 ajax,我想发布一些数据,如果模型成功保存,则将答案作为 JSON 对象返回。

这是我基于 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 模型节省和响应的正确方法,我将不胜感激。

【问题讨论】:

  • 我觉得这段代码的最后一行需要是:return HttpResponse("Not authorized.")

标签: javascript jquery ajax django


【解决方案1】:

您正在以标准格式编码发送 POST 数据。 dataType 属性没有指定要发送的数据类型,而是您希望接收的数据类型。如果你真的想从浏览器发送 JSON,你应该这样做:

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

【讨论】:

    【解决方案2】:

    jQuery 的 .ajax() 函数不会将数据作为原始 JSON 发布。它使用标准的表单编码格式(dataType 参数用于确定它期望来自服务器的响应 的格式)。

    因此,您应该这样做,而不是 json.loads() 调用:

    root = request.POST
    

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 2011-08-25
      • 2023-01-23
      • 2013-10-31
      • 2015-03-21
      • 2020-01-22
      • 2011-03-12
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多