[英]Sending data from Django Function to Javascript (no refreshing)
I have a django function 我有一个Django功能
@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 我想将r(这是从api到字典的响应)传递给我的页面main.html
def main(request):
return render(request, 'livestream/main.html')
how can I pass 'r' into a previously loaded page? 如何将“ r”传递到以前加载的页面? Main.html calls postdate with an ajax call.
Main.html使用ajax调用来调用postdate。 I would prefer if main.html doesn't refresh, but I'm ok if it has to.
我希望main.html不会刷新,但如果可以的话我可以。
I'm not sure if it matters, but I'm using a mysql server 我不确定是否重要,但我使用的是mysql服务器
Thanks 谢谢
views.py 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 livestream / main.html
$.ajax({
success: function(data) {
console.log(data); // here is your server response
}
});
Just change your view to return JSON: 只需更改您的视图以返回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. 然后,使用该JSON来执行客户端所需的任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.