无法通过AJAX更改/重定向页面

时间:2018-04-10 10:52:12

标签: javascript python jquery ajax django

所以我从post_ad()视图开始。当我提交boost_form时,视图会成功更改为options() - 其中模板更改为advertising/options.html。但是页面URL保持不变(/advertise/post/)。

当我执行我的ajax函数时,它成功触发第一个ajax调用(if request.POST.get('position'):)并打印相关变量。

然后我又进行了一次ajax调用(表单的onsubmit),然后在options()视图中调用第二个ajax:if request.POST.get('confirmed') == 'confirmed'。这会成功触发,pay()视图中的打印语句会触发,但我的终端不会显示POSTpay()的请求:

Position: 8 Duration: 106 Total price: 63
[10/Apr/2018 10:46:38] "POST /advertise/options/ HTTP/1.1" 200 13484
the final view
Pay
Pay ajax
[10/Apr/2018 10:46:40] "POST /advertise/options/ HTTP/1.1" 200 11615

然后不加载pay.html模板。有人可以告诉我为什么会这样吗?

这是我的代码:

def post_ad(request):
    boost_form = AdvertisePostForm(request.POST or None, request.FILES or None)
    if boost_form.is_valid():
        instance = boost_form.save(commit=False)
        if Post.objects.filter(hash=instance.hash).exists():
            instance.hash = random_string()

        instance.ad = True
        instance.save()
        return options(request)

    context = {
        'boost_form': boost_form
    }
    return render(request, 'advertising/post_ad.html', context)  

def options(request):
    latest = AdvertisePost.objects.order_by('-id')[0]
    ad = get_object_or_404(AdvertisePost, hash=latest.hash)

    if request.is_ajax():
        if request.POST.get('position'):
            position = request.POST.get('position')
            duration = request.POST.get('duration')
            total_price = request.POST.get('total_price')
            ad.position = position
            ad.duration = duration
            ad.total_price = total_price
            ad.save()
            print('Position:', position, 'Duration:', duration, 'Total price:', total_price)

        if request.POST.get('confirmed') == 'confirmed':
            print('the final view')
            return pay(request)

    context = {
        'ad': ad
    }

    return render(request, 'advertising/options.html', context)    

def pay(request):
    print('Pay') #prints
    if request.is_ajax():
        print('Pay ajax') #prints

    return render(request, 'advertising/pay.html', {})

我的模板

<form method="post" enctype="multipart/form-data" autocomplete="off" id="add_num_div">{% csrf_token %}
    ...
    <button class="submit_medium" type="submit" id="submit_boost">Next</button>
</form>

0 个答案:

没有答案