Passing JSON data to the front end using Django

后端 未结 5 2078
旧巷少年郎
旧巷少年郎 2021-01-01 02:42

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 t

5条回答
  •  梦毁少年i
    2021-01-01 03:00

    Sure, just setup a view that returns JSON and make a request to it. Here's a simple example:

    import json      
    from django.http import HttpResponse
    from django.template import Template, Context
    
    def ajax(request):
        """returns json response"""
        return HttpResponse(json.dumps({'foo': 'bar'}), mimetype='application/json')
    
    def index(request):
        """simple index page which uses jquery to make a single get request to /ajax, alerting the value of foo"""
        t = Template("""
        
          
           
           
         
        """)
        return HttpResponse(t.render(Context()))
    
    # urlconf
    urlpatterns = patterns('',
        (r'^$', index),
        (r'^ajax/', ajax),
    )
    

提交回复
热议问题