HTTP Content-Type Header and JSON

后端 未结 4 929
天涯浪人
天涯浪人 2020-11-30 20:23

I have always been trying to avoid using most of the HTTP protocol\'s properties for the sake of fear of the unknown.

However, I said to myself that I\'m going to fa

4条回答
  •  孤街浪徒
    2020-11-30 20:59

    The below code helps me to return a JSON object for JavaScript on the front end

    My template code

    template_file.json

    {
        "name": "{{name}}"
    }
    

    Python backed code

    def download_json(request):
        print("Downloading JSON")
        # Response render a template as JSON object
        return HttpResponse(render_to_response("template_file.json",dict(name="Alex Vera")),content_type="application/json")    
    

    File url.py

    url(r'^download_as_json/$', views.download_json, name='download_json-url')
    

    jQuery code for the front end

      $.ajax({
            url:'{% url 'download_json-url' %}'        
        }).done(function(data){
            console.log('json ', data);
            console.log('Name', data.name);
            alert('hello ' + data.name);
        });
    

提交回复
热议问题