I have a django function
@csrf_exempt
def postdata(request):
r = requests.post(url ,headers=headers, auth=auth, data=json.dumps(data))
return HttpResponse(r)
I want to pass r which is a dictionary response from a api to my page main.html
def main(request):
return render(request, 'livestream/main.html')
how can I pass 'r' into a previously loaded page? Main.html calls postdate with an ajax call. I would prefer if main.html doesn't refresh, but I'm ok if it has to.
I'm not sure if it matters, but I'm using a mysql server
Thanks
views.py
# data should be a list of dictionaries and not a queryset
return HttpResponse(json.dumps(data), content_type="application/json")
livestream/main.html
$.ajax({
success: function(data) {
console.log(data); // here is your server response
}
});
Just change your view to return JSON:
import json
from django.http import HttpResponse
@csrf_exempt
def postdata(request):
r = requests.post(url ,headers=headers, auth=auth, data=json.dumps(data))
return HttpResponse(json.dumps(r, ensure_ascii=False),
content_type='application/json')
Then use that JSON to do whatever you need on the client-side.
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.