Search code examples
javascriptpythonjqueryjsonget

How to use $.getJSON in JavaScript to retrieve a python file data?


How to use $.getJSON in JavaScript to retrieve a python file data?

$.getJSON('data.py', function (keyData) {
//code
})

data.py

import urllib.request, json 
def jsonURL():
    with urllib.request.urlopen("https://cdn.rawgit.com/highcharts/highcharts/057b672172ccc6c08fe7dbb27fc17ebca3f5b770/samples/data/usdeur.json") as url:
    data = json.loads(url.read().decode())
    return data

Solution

  • Use $.ajax instead to get the Python file:

    $.ajax({
        type: "get",
        url: "data.py",
        success: function(response) {
            //Do stuff
        }
    });
    

    This will query the Python file. However, as shown here, you need to tell your web server to execute the file instead of returning the contents.