简体   繁体   中英

Pass Python Requests (in Django views.py) Json Data to Javascript

I have this python code, which fetches json and parses it:

from django.http import HttpResponse
import json, requests

def find(request):
    context = {}
    platformUrl = 'https://www.igdb.com/api/v1/platforms'
    platformReq = requests.get(platformUrl, headers={'Authorization': 'Token token="1234"'})
    platformData = json.loads(platformReq.text)
    platformList = platformData['platforms']
    print platformList

It outputs this with the print statement:

[{u'slug': u'saturn', u'id': 32, u'name': u'Sega Saturn'}, {u'slug': u'mac', u'id': 14, u'name': u'Mac'}, {u'slug': u'vc', u'id': 47, u'name': u'Virtual Console (Nintendo)'}

I would like to pass that data to javascript and have the ID and name from the json put in this javascript. (selectize.js) This would probably require some type of for loop, could be javascript, or even djangos?:

    options: [
    {id: 1, title: 'Spectrometer'},
    {id: 2, title: 'Star Chart'},
    {id: 3, title: 'Electrical Tape'}
]

Thanks

EDIT: Following @satoru's link, I looked into it, and updated my code to this:

    from django.http import HttpResponse
import json, requests

def find(request):
    context = {}
    platformUrl = 'https://www.igdb.com/api/v1/platforms'
    platformReq = requests.get(platformUrl, headers={'Authorization': 'Token token="1234"'})
    platformList = json.dumps(platformData)

    print platformList
    return render_to_response('find.html',{'platformList':platformList})

It now outputs this:

{"platforms": [{"slug": "saturn", "id": 32, "name": "Sega Saturn"}, {"slug": "mac", "id": 14, "name": "Mac"}, {"slug": "vc", "id": 47, "name": "Virtual Console (Nintendo)"}

How would I then pass that into javascript?

If the API already return a JSON-encoded response, you can just use platformReq.text . After passing it to render_to_response , you have access to a JSON-encoded string in your template.

Now you can design your Javascript module to be configurable with an object, for example:

<script src="my_module.js"></script>
<script>
   MyModule.initialize({{ json_encoded }})
</script>

Check out this template library to convert your platform list to a JSON object from within the template

Example(Inside your template):

    <script src="your_standalone_js.js">
    <script>
        var js_variable = {{platformList | jsonify }};
        function_in_standalone_js(js_variable);
    </script>

your_standalone_js.js:

    var function_in_standalone_js = function(js_variable){
        var options = js_variable['platforms'];
        //What ever you need to do with options
    };

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM