python - Javascript to Django views.py? -
this may sound simple, how send data javascript array in index.html template views.py?
when user clicks "recommend" button, code calls function accesses database , prints name on template.
def index(request): if(request.get.get('recommend')): sql_handler.recfunc() context['name'] = sql_handler.name return render(request, 'polls/index.html', context)
i have array of checkbox values in javascript calculated after user presses "recommend". want send index view , use parameter function.
so:
def index(request): if(request.get.get('recommend')): sql_handler.recommend() context['name'] = sql_handler.name //something?? tags = check_array_javascript context['tags'] = tags return render(request, 'polls/index.html', context)
how can this? i've been searching similar questions, i'm new django , web development in general, either did not understand answers or didn't me.
alright, sending data client (javascript) backend (your django app) need employ called ajax, stands asynchronous javascript , xml. allowing communicate backend services without need of having reload page, which, have using normal post or put form submission.
the easiest implementation using jquery. jquery first , foremost dom manipulation library since inception has grown encompass more that.
a jquery ajax call looks this.
$(document).ready(function() { $.ajax({ method: 'post', url: '/path/to/your/view/', data: {'yourjavascriptarraykey': yourjavascriptarray}, success: function (data) { //this gets called when server returns ok response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); });
this can checked in views.py
def index(request): if request.is_ajax(): #do request_data = request.post return httpresponse("ok")
Comments
Post a Comment