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: {}>
任何一個可以告訴我爲什麼數據沒有被髮送到服務器和/或爲什麼我不能在我看來訪問它?
聽起來不錯,但是我收到以下錯誤:' UnboundLocalError:在賦值之前引用的局部變量'json'。我在文件中執行'import json'。 – deelaws 2013-03-05 18:09:05
在application/json上使用「application/x-www-form-urlencoded」有沒有優勢? – deelaws 2013-03-05 18:12:14
糟糕,對不起,我用json替換了simplejson,並忘記了那裏已經有一個名爲json的變量。固定。 – 2013-03-05 18:43:45