2013-03-05 6 views
2

단일 아약스 호출을 작성하려고합니다. 아약스 호출은 서버로 보내지지만 보내고있는 데이터는 뷰의 요청 개체에서 사용할 수 없습니다. request.post을 인쇄하면 <QueryDict: {}>이됩니다. 서버에 데이터가 전송되지 않습니다. 크롬에서 요청 페이로드에서 볼 수 있기 때문에 브라우저가 데이터를 전송하고 있음을 알고 있습니다.데이터가 장고보기에 jquery .ajax()를 사용하여 전송되지 않았습니다.

스크립트

$("#chatform").submit(function(e) { 
    e.preventDefault(); 
    //serialText = $(this).serialize(); 
    var userText = $("#usertext").val(); 
    var xmlRequest = $.ajax({ 
      type: "POST", 
      url: "/sendmessage/", 
      data: {'tosend': userText}, 

      //dataType: 'json', 
      contentType: "application/json; charset=utf-8", 
      success: function(data){ 
       appendMessageSent(data.messagesent); 
      } 
    }); 
}); 

view.py :

def send_message(request): 
    if request.is_ajax(): 
     message = "The hell with the world" 

     print request.POST 
     json = simplejson.dumps(
      {'messagesent' : request.POST['tosend']+"This is how we do it"} 
     ) 
     return HttpResponse(json, mimetype='application/javascript') 

HTML

<form id="chatform" action="" method="POST" > 
     <input type='hidden' name='csrfmiddlewaretoken' value='8idtqZb4Ovy6eshUtrAiYwtUBboW0PpZ' /> 
     <input type="text" name="chatarea" id="usertext"/> 
     <input type="submit" value="Send"> 
</form> 

나는 키 01 없다는 오류은 request.post dict에 없습니다. 데이터가 서버로 전송되지 않는 이유

MultiValueDictKeyError: "Key 'tosend' not found in <QueryDict: {}>

어떤 사람은 말해 줄 수 및/또는 왜 내보기에 액세스 할 수 없습니다?

답변

7

양식 데이터를 request.POST에 표시하려면 contentType: "application/x-www-form-urlencoded"을 사용하십시오.

def send_message(request): 
    if request.is_ajax(): 
     message = "The hell with the world" 

     data = json.loads(request.body) 
     result = json.dumps({'messagesent' : data['tosend'] + "This is how we do it"}) 
     return HttpResponse(result, mimetype='application/javascript') 
+0

좋은 소리 그러나 나는 다음과 같은 오류가 점점 오전 : 당신이 application/json를 사용하는 경우

, 당신은 (장고> = 1.4, 장고 < 1.4 request.bodyrequest.raw_post_data) 원시 데이터를 직접 분석해야' UnboundLocalError : 지역 변수 'json'이 할당 전에 참조 됨. 파일에서'import json'을하고 있습니다. – deelaws

+0

application/json보다 "application/x-www-form-urlencoded"를 사용하면 이점이 있습니까? – deelaws

+0

죄송합니다. simplejson을 json으로 대체했으며 json이라는 변수가 이미 있다는 것을 잊어 버렸습니다. 결정된. –

관련 문제