Django ajax HttpResponse json错误意外的令牌d

时间:2014-01-21 13:47:47

标签: jquery python ajax django json

我正在尝试使用medium-editor做一个Django ajax HttpResponse json。

view.py

def test(request, union_id):
if request.is_ajax():
    t = Union.objects.get(id=union_id)
    message = json.loads(request.body)
    t.description = message['description']['value']
    t.save()
    return HttpResponse(message, mimetype="application/json")
else:
    message = "Not Ajax"
    return HttpResponse(message)

Jquery(已更新)

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $('#savecontentObj').click(function() {
        var contentObj = editor.serialize();
        obj = JSON.stringify(contentObj);
        $.ajax({
          url:"update",
            type: "POST",
            data: obj,
            dataType: "json",
            contentType: "application/json",
            success:function(response){
                console.log('success');
            },
            complete:function(){
                console.log('complete');
            },
            error:function (xhr, textStatus, thrownError){
                console.log(thrownError);
                console.log(obj);
            }
        });
    });

的console.log

SyntaxError {stack: (...), message: "Unexpected token d"}
{"description":{"value":"<p>dddddd</p>"}}
complete 

它正在为数据库保存'description',但我没有在httpresponse中取得成功,正如您在console.log中看到的那样。

非常感谢!

更新

url.py

url(r'^(?P<union_id>\d+)/update$', views.test),

1 个答案:

答案 0 :(得分:0)

def test(request, union_id):
if request.is_ajax():
    t = Union.objects.get(id=union_id)
    t.description = request.POST.get('description',None)
    t.save()
    HttpResponse(json.dumps(dict(status='updated')), mimetype="application/json")
else:
    message = "Not Ajax"
    HttpResponse(json.dumps(dict(status="Not Ajax")), mimetype="application/json")

$('#savecontentObj').click(function() {
        var contentObj = editor.serialize();
        $.ajax({
          url:"update",
            type: "POST",
            data: contentObj,
            dataType: "json",
            success:function(data){
                console.log(data.success);
            },
            complete:function(){
                console.log('complete');
            },
            error:function (xhr, textStatus, thrownError){
                console.log(thrownError);
                console.log(obj);
            }
        });
    });

确保您的ajax网址不符合您的视图方法,并且csrf标记必须存在于序列化值中。