Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Send Fetch Post With Data Using Body

#the template in templates/??

function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');


async    function send()
    {

      
        
let r =      await fetch('/blog/third', {method: 'POST', credentials: 'same-origin', headers:{'Accept': 'application/json',    'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken}, body: JSON.stringify({'post_data':'Data to post'})});
let res = await r.json();
console.log(res.my_data);

    }

#the view in views/???
#the key difference between express is import json, json.load(request)['the key/name of the data], then create your own json and JsonResponse it back

import json

#.......


def third(request):
    if request.method == "POST":
        data_from_post = json.load(request)['post_data']
        data = {
                'my_data': data_from_post
        }
        
        return JsonResponse(data)
   
  
    
Source by www.brennantymrak.com #
 
PREVIOUS NEXT
Tagged: #Send #Fetch #Post #With #Data #Using #Body
ADD COMMENT
Topic
Name
8+7 =