2013-03-05 61 views
2

我試圖創建一個Ajax調用。 ajax調用被髮送到服務器,但是我發送的數據在視圖中的請求對象中不可用。當我打印request.post時,它給出<QueryDict: {}>。沒有數據正在發送到服務器。我知道瀏覽器正在發送數據,因爲我可以在chrome中的請求有效負載中查看它。使用jQuery .ajax()發送到Django視圖的數據

腳本:

$("#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字典中找不到字典。

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

任何一個可以告訴我爲什麼數據沒有被髮送到服務器和/或爲什麼我不能在我看來訪問它?

回答

7

要使表單數據出現在request.POST中,請使用contentType: "application/x-www-form-urlencoded"

如果使用application/json,你必須自己分析的原始數據(request.raw_post_data在Django < 1.4,request.body在Django> = 1.4):

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

聽起來不錯,但是我收到以下錯誤:' UnboundLocalError:在賦值之前引用的局部變量'json'。我在文件中執行'import json'。 – deelaws 2013-03-05 18:09:05

+0

在application/json上使用「application/x-www-form-urlencoded」有沒有優勢? – deelaws 2013-03-05 18:12:14

+0

糟糕,對不起,我用json替換了simplejson,並忘記了那裏已經有一個名爲json的變量。固定。 – 2013-03-05 18:43:45