未使用jquery.ajax()将数据发送到Django视图
我正在尝试创建一个ajax调用。ajax调用被发送到服务器,但我发送的数据在视图中的请求对象中不可用。当我打印未使用jquery.ajax()将数据发送到Django视图,django,jquery,django-views,Django,Jquery,Django Views,我正在尝试创建一个ajax调用。ajax调用被发送到服务器,但我发送的数据在视图中的请求对象中不可用。当我打印request.post时,它会给出。没有数据被发送到服务器。我知道浏览器正在发送数据,因为我可以在chrome的请求负载中查看数据 脚本: $("#chatform").submit(function(e) { e.preventDefault(); //serialText = $(this).serialize(); var userText = $("#u
request.post
时,它会给出
。没有数据被发送到服务器。我知道浏览器正在发送数据,因为我可以在chrome的请求负载中查看数据
脚本:
$("#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);
}
});
});
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')
view.py:
$("#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);
}
});
});
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>
我收到一个错误,说明在请求中找不到键tosend
。post
dict
多值DictKeyError:“在
有人能告诉我为什么数据没有发送到服务器和/或为什么我无法在视图中访问它吗?要使表单数据出现在
请求中,请使用内容类型:“application/x-www-form-urlencoded”
如果使用application/json
,则必须自己解析原始数据(django=1.4中的request.raw\u post\u data
):
这听起来不错,但我得到了以下错误:UnboundLocalError:assignment之前引用的局部变量“json”
。我正在文件中导入json
。使用“application/x-www-form-urlencoded”是否有好处“在application/json上?对不起,我用json替换了simplejson,忘记了已经有一个名为json的变量。修正了。在您的情况下,唯一的优势是您不必自己解析任何内容。在jQuery(1.7)中,默认的contentType似乎是“application/x-www-form-urlencoded;charset=UTF-8”,所以我所要做的就是从AJAX调用中删除contentType:“application/json”以使其正常工作。