【问题标题】:How can I skip to a template and render the request data to it using ajax?如何跳到模板并使用 ajax 将请求数据呈现给它?
【发布时间】:2018-03-02 07:07:18
【问题描述】:

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

我的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。

但是server.html页面没有跳转到payment.html,不知道怎么实现。

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

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

【问题讨论】:

    标签: python html ajax django


    【解决方案1】:

    您需要在进行任何逻辑之前检查 AJAX 标头并返回 JsonResponce request.is_ajax() 更多内容请关注documentation

    def server_payment(请求):

    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')
    

    【讨论】:

    • 我阅读了文档,发现没有任何用处。怎么用它来实现,能不能说的详细点?
    • 我想在server_payment()函数中重定向到app_admin/payment.html并在模板中渲染请求数据。你返回JsonResponse,页面不会切换。
    • 在这种情况下,据我所知-您应该更改 URL windows.location...
    • 我尝试使用self.location=xxx,但我现在无法传递数据。
    • 你应该在Js代码中更改location,我认为是success_func
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 2012-11-02
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多