如何使用ajax跳转到模板并将请求数据呈现给它?

时间:2017-09-21 04:05:55

标签: python html ajax django

这是第一页,在那里我可以使用ajax来请求url,并将请求数据传递给它。

enter image description here

我的ajax代码如下:

     $.ajax({
         type:'post',
         url:'/app_api/server_payment/',
         contentType:'application/json',
         data:JSON.stringify({'params':buy_data}),
         dataType:'json',
         success:success_func
     })
     function success_func(response){
         console.log(response)
     }

在views.py中:

def server_payment(request):

    if request.method == 'POST':
        is_login = request.session['is_login']

        if is_login:

            print ('server_payment_2 ', is_login)  # it prints 
            return render(request, 'app_admin/payment.html')

        else:
            return render(request, 'frontend/login.html')

在views.py中,我想渲染payment.html并跳过它。

这是我的payment.html。

enter image description here

但是server.html页面没有跳到payment.html,我不知道如何实现它。

我尝试使用self.location=/app_api/server_payment/但我无法使用post方法传递数据。

第一张快照中有一些详细信息。

1 个答案:

答案 0 :(得分:0)

在制作任何逻辑并返回JsonResponce之前,您需要检查AJAX标头 request.is_ajax() documentation

中的更多内容

def server_payment(request):

if request.method == 'POST':
    is_login = request.session['is_login']

    if is_login:

        print('server_payment_2 ', is_login)  # it prints
        if request.is_ajax():
            return JsonResponse({'foo': 'bar'})
        return render(request, 'app_admin/payment.html')

    else:
        return render(request, 'frontend/login.html')
相关问题