简体   繁体   English

Django:如何在 AJAX POST 请求中检索两个不同变量的值?

[英]Django: How to retrieve in an AJAX POST request the value of two different variables?

I'm trying to send to my Django view two values from two different dropdowns but it doesn't work.我正在尝试将两个不同下拉列表中的两个值发送到我的 Django 视图,但它不起作用。 Only the first dropdown value is sent to the view.只有第一个下拉值被发送到视图。

Let's say I have the following view:假设我有以下观点:

def MyView(request):

    if request.method == 'POST' and request.is_ajax:

        result_1 = request.POST.get('d1')
        print(result_1)
        result_2 = request.POST.get('d2')
        print(result_2) 

And this is the html code:这是 html 代码:

<script type="text/javascript">
  function dropdownChange () {
    var selectedRegion = $(".toChange option:selected").val();
    $.ajax({
            url: '/myApp/templates/',
            type: 'POST',
            data: {'d1': selectedRegion},
            }
    }); 
}
$(".toChange").change(dropdownChange);
</script>

  <select name="d1" class="toChange">
    <option val="1"> 1 </option>
    <option val="2"> 2 </option> 
  </select>

 <select name="d2">
    <option val="3"> 3 </option>
    <option val="4"> 4 </option> 
  </select>

When the dropdown d1 faces a change, I want both d1 and d2 values to be sent to my view.当下拉菜单 d1 发生变化时,我希望将 d1 和 d2 值都发送到我的视图中。 The value of d1 is properly captured but d2 (so result_2) shows "[]". d1 的值被正确捕获,但 d2(因此 result_2)显示“[]”。 How can I capture the two variables?如何捕获这两个变量?

Simply add it in the data variable:只需将其添加到数据变量中:

var selectedRegion = $(".toChange option:selected").val();
var selectedRegion2 = $("select[name=d2] option:selected").val();
$.ajax({
    url: '/myApp/templates/',
    type: 'POST',
    data: {'d1': selectedRegion, 'd2': selectedRegion2},           
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM