2014-01-21 1 views
0

medium-editor을 사용하여 장고 아약스 HttpResponse json을 수행하려고합니다.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를 데이타베이스에 '설명'을 절약하지만 성공을 달성하고 있지 않다

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

(업데이트)

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 console.log에서 볼 수 있듯이 httpresponse에 있습니다.

감사합니다.

업데이트

url.py

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

'데이터 : JSON.stringify (obj)'데이터를 문자열로 변환 해보십시오. – mariodev

+0

고마워, 나는 이미 여기에서 그것을했다 :'obj = JSON.stringify (contentObj);' –

+0

오, 그래, 미안. – mariodev

답변

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); 
      } 
     }); 
    }); 

확인하십시오 아약스 URL이보기 방법도 CSRF 토큰이 직렬화 값에 존재해야합니다에 따라되지되어 있는지 확인합니다.

+0

이 뷰에서 나는 IntegrityError를 얻는다 : (1048, "컬럼 'description'은 null이 될 수 없다)'. 내 url.py 코드 –

+0

으로 업데이트하면 import pdb; pdb.set_trace() 줄을 t = Union.objects.get (id = union_id) 뒤에 배치하면 코드를 디버깅 할 수 있습니다. 당신은 디버깅 콘솔을 얻었습니다. 당신은 request.POST에 존재 설명을 확인할 수 있습니다. serialize 값을 확인하지 않으면. –

+0

'return HttpResponse (json.dumps (dict (status = 'updated')), mimetype = "application/json")'성공에 성공했습니다. 고맙습니다. @Yogesh,이 실험을 계속합니다 –