我想要做一個Django ajax HttpResponse json使用medium-editor。Django ajax HttpResponse json錯誤意外的令牌d
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
這是節約 '說明' 到數據庫,但我不會取得成功在httpresponse中,你可以在console.log中看到。
非常感謝!確保您的AJAX的網址是不是按你的觀點和方法也CSRF令牌必須連載值存在
更新
url.py
url(r'^(?P<union_id>\d+)/update$', views.test),
嘗試使數據字符串化:'data:JSON.stringify(obj)'。 – mariodev
謝謝,我已經這樣做了:'obj = JSON.stringify(contentObj);' –
哦對不起,我錯過了。 – mariodev