简体   繁体   中英

Sending data to the server via XMLHttpRequest in Django

I am designing a web app where users can post content to a feed. I usually send the post and the post data to the server via an 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()

On the server I then access the data with

x = request.GET['x']

But I have run into some problems using this method especially when the post text contains an '#'. I was wondering if I can send the data using

request.send(data)

But I don't know how to access that data in the view function... How can I access data in my view function that has been send to the server using request.send(data)????

I am not sure, because the question is not entirely clear to me.

If what you want to do is accessing the payload of the request you receive, then you need to know that

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. This is necessary because some HTML form elements, notably, pass multiple values for the same key 1 .

Therefore you can access the 'data' payload by writing something like this data= request.POST.get('data','') .

If you want to send a # in a url parameter to the backend you have to encode it

"/sent_new_post?x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user)

If you want to send the data in the post body you'll have to use request.POST to access the data, you will still have to encode the data you're sending.

request.send("x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM