使用Django将JSON数据传递到前端 [英] Passing JSON data to the front end using Django
问题描述
如果我想要使用Django框架或Python,有没有办法将JSON对象传递到Web模板的前端?发送一个具有两个数组的对象作为属性(假设 xvalues
和 yvalues
),我将如何使用JavaScript或jQuery进行Ajax调用来获取具有属性的对象?
补充zeekay答案,如果你想只发送一个对象,你可以做一个json转储,例如:
从django.utils import simplejson
def my_ajax_view(request):
如果没有request.is_ajax():
raise Http404
data_dict = getmydata()#lets supose是一个dict
返回HttpResponse(simplejson.dumps(data_dict))
这样,您将通过您的ajax成功获得该数据并且做任何你想要的。
你可以发送列表t oo,当你收到你的回应有时候你将需要做一个JSON.parse的数据(有时导致当你发送一个字典,我认为没有必要)
Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?
For example, if I want to send an object that has two arrays as properties (let's say xvalues
and yvalues
), how would I be able to use JavaScript or jQuery to do an Ajax call to obtain the object that has the properties?
Complementing zeekay answer, if you want to send only an object you could do a json dump, for example:
from django.utils import simplejson
def my_ajax_view(request):
if not request.is_ajax():
raise Http404
data_dict = getmydata() #lets supose is a dict
return HttpResponse(simplejson.dumps(data_dict))
That way you will receive that data via your ajax success and do whatever you want with it.
You can send over lists too, when you receive your response sometimes you will need to do a JSON.parse on data (sometimes cause when you send a dictionary I think is not necessary)
这篇关于使用Django将JSON数据传递到前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!