简体   繁体   中英

How to call/use data returned by python function in javascript?

I've defined a function in views.py like this

def ma_fonction_bokeh(request, numero = None):
    CDR_COMMON = settings.DBCON[settings.MONGO_CDRSTATS['CDR_COMMON']]
    acc = CDR_COMMON.find()
    donnees = [] # on initialise une liste
    for i in acc:
        if i['accountcode'] == numero:
            donnees.append([calendar.timegm(i["start_uepoch"].timetuple()), i["duration"]])

    data = simplejson.dumps(donnees)

    return render(request,"frontend/mongraphe.html", {"name": numero, "data": data})

Then in the mongraphe.html file I've created a javascript code for a plot that I got from http://www.highcharts.com/stock/demo/dynamic-update What I want is to customize the plot with my own data which is returned by the function that I defined at first... so how can I do that? I've tried the ajax function but without result

You can transfer data from your Python code to JavaScript in several ways.

The "proper" way is to create another endpoint which only returns the JSON data and then use an AJAX request (for example, jQuery.getJSON(…) ) to request it.

A quicker way is to modify your template ( frontend/mongraphe.html ) to include the JSON data as a variable. Since you didn't specify what Python library you're using, I'm going to assume you're using something like Django. Here's what you would add to your template to make the data available in JavaScript:

<script>
var data = {{data}};
</script>

Make sure that you put the <script> tag above some place before you try to access the data. The {{data}} part will output the JSON string that you created in your Python script so that the final output will be something like var data = {"hello": "world"};

Now you should be able to access the data variable in your JavaScript and put the data into the Highcharts.js chart.

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