从Javascript接收数据后重定向到新页面 [英] Redirect to new page after receiving data from Javascript

查看:37
本文介绍了从Javascript接收数据后重定向到新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Javascript数组传递给Django视图.这可行,但是我想操纵该数据并将其显示在单独的url中.因此,我有一个产品页面,您可以在其中选择商品.提交表单后,将调用此javascript,我希望它重定向到购物车页面:

I'm trying to pass a Javascript array to my Django views. This works, but I would like to manipulate that data and display it in a separate url. So I have a products page, where you select items. When the form is submitted, this javascript is called, and I want it to redirect to a cart page:

$("#getArr").submit(function(){
  var data = {'ab[]' : chosen};
  $.post('cart/', data, function(response){
    if(response == 'success'){ 
      window.location.href="cart/" // references my views
    }
    else{ 
      alert('Error! :('); 
    }
  });
});

views.py

def cart(request):
  if request.method == 'POST':
    chosen = request.POST.getlist('ab[]')
    print(chosen, file=sys.stderr)
    template = loader.get_template('o/cart.html')
    context = {'prodChosen': chosen,
                'e': "hy"}
    return HttpResponse('success')
    # return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('o/cart.html')
    context = {}
    return HttpRepsonse('fail')
    # return HttpResponse(template.render(context, request))

就像注释掉的HttpResponse行中一样,我需要将数据传递到我的cart.html(这将是我的模型之一中的对象).我不知道如何将数据传递到购物车页面.

Like in the commented out HttpResponse lines, I need to pass data to my cart.html (it will be objects from one of my models). I have no idea how to pass data to my cart page.

print(chosen,file = sys.stderr)行非常有用.以前,当我有使用注释掉的代码返回HttpResponse行时,它会将所需的数组和一个空数组都打印到我的终端上.但是,使用此新代码,所需的数组会打印出来,但不会重定向到新页面.我不确定为什么会这样,但是我确实知道,在我较早的尝试中打印出的空数组也意味着我的购物车页面没有收到正确的数组数据.

The line print(chosen, file=sys.stderr) has been quite useful. Previously, when I had code that used the commented out return HttpResponse lines, it printed to my terminal both the desired array and an empty one. However, with this new code, the desired array prints out but it doesn't redirect to the new page. I'm not sure why this is happening, but I do know the fact the empty array printed out at as well in my earlier attempt meant my cart page wasn't receiving the correct array data.

我需要将模型对象传递到新的html页面,(据我所知)我无法通过javascript

I need to pass model objects to the new html page, which (from what I know) I can't do through javascript

index.html

<form id="getArr" method="POST">
      {% csrf_token %}
      <button type='submit' id="checkCart">Check Added Items</button>
</form>

推荐答案

如果我正确理解了这个问题,那么我认为您完全可以通过使用JQuery添加一个额外的步骤.

If I understand the question correctly, I think you are adding an extra step by using JQuery at all.

解决方案#1 -在jQuery中动态创建一个表单元素,然后将该表单提交给您的Django端点.通常在Django渲染模板中.

Solution #1 - Create a form element on the fly in jQuery and submit that form to your Django endpoint. In Django render template normally.

JavaScript

$("#getArr").submit(function(){
  var url = 'cart/';
  var form = '<form action="' + url + '" method="post">';
  for (var i = 0; i < chosen.length; i++) {
      form += '<input type="hidden" name="ab[]" value="' + chosen[i] + '" />'
  };
  form += '</form>'
  var form_element = $(form);
  $('body').append(form_element);
  form_element.submit();
});

然后在您的视图中,只需照常返回模板:

And then in your view, simply return the template as usual:

views.py

def cart(request):
  if request.method == 'POST':
    chosen = request.POST.getlist('ab[]')
    print(chosen, file=sys.stderr)
    template = loader.get_template('o/cart.html')
    context = {'prodChosen': chosen,
                'e': "hy"}
    return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('o/cart.html')
    context = {}
    return HttpRepsonse('fail')
    # return HttpResponse(template.render(context, request))

解决方案#2 -使用jQuery

Solution #2 - Use jQuery .load() function function and submit that form to your Django element. In Django render template normally (or as a snippet to avoid repeating other page elements).

JavaScript

$("#getArr").submit(function(){
  $('#main-content-div').load('cart/', $("#getArr").serialize());
});

views.py

def cart(request):
  if request.method == 'POST':
    chosen = request.POST.getlist('ab[]')
    print(chosen, file=sys.stderr)
    template = loader.get_template('o/cart.html')
    context = {'prodChosen': chosen,
                'e': "hy"}
    return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('o/cart.html')
    context = {}
    return HttpRepsonse('fail')
    # return HttpResponse(template.render(context, request))

解决方案#3 -使用元素名称 ab [] 创建一个典型的HTML表单,并将该表单提交到Django端点.通常在Django渲染模板中.

Solution #3 - Create a typical HTML form with elements name ab[] and submit that form to your Django endpoint. In Django render template normally.

表格:

HTML

<form id="getArr" action="cart/" method="POST">
    <input type="text" name="ab[]" value="product_id_1"/>
    <input type="text" name="ab[]" value="product_id_2"/>
    <input type="text" name="ab[]" value="product_id_3"/>
    <input type="submit" value="Submit" />
</form>

一些Java脚本将元素添加到表单中:

Some Javascript to add elements to the form:

JavaScript

$('.add_product').click(function(){
    $('#getArr').append('<input type="hidden" name="ab[]" value="' + $(this).attr('product_id') + '"/>')
})

Django视图:

views.py

def cart(request):
  if request.method == 'POST':
    chosen = request.POST.getlist('ab[]')
    print(chosen, file=sys.stderr)
    template = loader.get_template('o/cart.html')
    context = {'prodChosen': chosen,
                'e': "hy"}
    return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('o/cart.html')
    context = {}
    return HttpRepsonse('fail')
    # return HttpResponse(template.render(context, request))

这篇关于从Javascript接收数据后重定向到新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆