jquery - Django load model database values using ajax -
i working on side project using django framework. need direct page website when user clicks <div>
area without refreshing page. searched around , found ajax should option. followed questions on stackoverflow didn't work. want is: user clicks div region,
<div onclick=window.open("{{link}}");>
link variable django/views; without refreshing page, if user clicks page again, direct link. link generated database , randomly selected after each click.
my template using jquery/ajax:
$(document).ready(function(){ $("#mydiv").on("click",function(){ $.ajax({ url:"http://127.0.0.1:8000/" success:function(){ window.open({{link}}); } } } }
views.py
def index(request): modellinks=model_link.objects.values_list('links',flat=true) link=random.choice(modellinks) return render(request,'myapp/index.html',{'link':link})
adding problems... problem when used above template , views.py, clicking div area, doesn't link website. without using ajax, can make div area link other website using div onclick event. think may have wrong above ajax in template or views.py when using ajax.
did write template right? how modify views.py connect views.py , ajax?
you'll want try along these lines:
views.py:
from django.http import jsonresponse def index(request): modellinks = model_link.objects.values_list('links', flat=true) link = random.choice(modellinks) data = { 'link': link } return jsonresponse(data)
ajax:
$(document).ready(function(){ $("#mydiv").click(function(e){ e.preventdefault(); $.ajax({ url: "http://127.0.0.1:8000/", data: { csrfmiddlewaretoken: "{{ csrf_token }}", }, datatype: "json", success: function(data){ window.open(data.link) }, error: function (rs, e) { alert('sorry, try again.'); } }); }); });
html:
<button id="mydiv" type=submit>open link</button>
Comments
Post a Comment