【发布时间】:2019-06-20 02:20:16
【问题描述】:
我是 Django 的新手,我正在尝试创建一个短 url 网站,我使用 Ajax 在不刷新页面的情况下缩短了 url,我在 view.py 中创建了一个唯一的 url,但我不知道如何打印创建使用JsonResponse的网址请告诉我我将如何做到这一点
index.html:
<form method="POST" id="shorten" class="form-inline">{% csrf_token %}
<div class="form-group">
<input type="url" name="url" placeholder="Your URL Here" required="required" class="form-control input-lg" id="url"/>
<button id="submit" class="btn-captcha" style="display: flex;" type="submit"><img src={% static "img/right-arrow.png" %} alt=""/></button>
<div> {{url}}<div>
</div>
</form>
阿贾克斯:
<script>
$(document).on('submit','#shorten',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: '/shorturl/',
data:{
url:$('#url').val(),
csrfmiddlewaretoken : $('input[name=csrfmiddlewaretoken]').val()
},
success:function(){
alert("ok")
}
});
});
</script>
views.py:
def shorturl(request):
if request.method == 'POST':
url = request.POST.get('url')
obj = userurltable(url = url)
obj.save()
obj2 = userurltable.objects.last()
url_id = obj2.id
code = short_url.encode_url(url_id)
shortened_url = settings.BASEURL + code
dic = {"url": shortened_url }
# I want to send this dic to my html page and
# print the url in html I don't wanna use render
# because I am submitting the form using ajax
那么如何在不刷新页面的情况下在<div>{{url}}</div> 中打印短网址?
【问题讨论】: