![](/img/trans.png)
[英]XMLHttpRequest is not sending POST data to Django server
[英]Sending data to the server via XMLHttpRequest in Django
我正在设计一个 web 应用程序,用户可以在其中将内容发布到提要。 我通常通过 XMLHttpRequest 将帖子和帖子数据发送到服务器。
request = new XMLHttpRequest()
var user = 'current user'
var post = 'some text'
request.open("POST", "/sent_new_post?x=" + post + "&user=" + user)
request.setRequestHeader("X-CSRFToken", csrftoken);
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request. onload = () => { // do stuff when response comes back }
request.send()
然后在服务器上访问数据
x = request.GET['x']
但是我在使用这种方法时遇到了一些问题,尤其是当帖子文本包含“#”时。 我想知道我是否可以使用发送数据
request.send(data)
但我不知道如何访问视图 function 中的数据...如何访问我的视图 function 中使用 request.send(data) 发送到服务器的数据????
我不确定,因为这个问题对我来说并不完全清楚。
如果您要做的是访问您收到的请求的有效负载,那么您需要知道
In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict, a dictionary-like class customized to deal with multiple values for the same key. 这是必要的,因为某些 HTML 表单元素,特别是为同一个键1传递多个值。
因此,您可以通过编写类似data= request.POST.get('data','')
内容来访问'data'
有效负载。
如果您想将 url 参数中的#
发送到后端,您必须对其进行编码
"/sent_new_post?x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user)
如果你想在帖子正文中发送数据,你必须使用request.POST
来访问数据,你仍然需要对你发送的数据进行编码。
request.send("x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.