如何访问复选框值并将其传递给Ajax [英] How to access and pass checkbox values to ajax

查看:63
本文介绍了如何访问复选框值并将其传递给Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下方式,但是请求过程像

I tried in the following way but requesting is going like

[21/Sep/2018 14:48:45] "GET /buildknowledge/sharing?bid=75&sharewith=16,17 HTTP/1.1" 500 14382

要求:

  [21/Sep/2018 14:48:45] "GET /buildknowledge/sharing?bid=75&sharewith=16&sharewith=17 HTTP/1.1" 500 14382

我尝试了以下方式:

表格:

 <div class="modal-body">
              <p class="statusMsg"></p>
              <form role="form">{% csrf_token %}                      
                <div class="form-check">
                    <label for="sharewith">Share with</label></br>
                 {% for sharewith in sharewithonly %}
                   <input class="form-check-input position-static" name="mycheckboxes[]" id="myCheckboxes" type="checkbox"  value="{{ sharewith.id }}">
                     <label>{{ sharewith.email }}</label></br>
                  {% endfor%}
                </div>
            </form>
        </div>


        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary submitBtn" onclick="shareForm()">SUBMIT</button>
        </div>
    </div>
</div>

Ajax和js部分:

Ajax and js part:

  function shareForm() {
    console.log(node_name);
    var token = '{{csrf_token}}';

    var sharewith =getChecked();
        function getChecked(){
            var items=document.getElementsByName('mycheckboxes[]');
            var selectedItems=new Array();
            for(var i=0; i<items.length; i++)
            {
                if(items[i].type=='checkbox' && items[i].checked==true)
                    selectedItems.push(items[i].value);
            }
            return(selectedItems);
        };



        $.ajax({
            headers: {"X-CSRFToken": token},
            type: 'GET',
            url: 'sharing',
            dataType: "json",
            traditional: true,
            data: 'sharewith=' + sharewith ,
            beforeSend: function () {
                $('.submitBtn').attr("disabled", "disabled");
                $('.modal-body').css('opacity', '.5');
            },
            success: function (msg) {
                if (msg == 'ok') {
                    $('#inputName').val('');
                                }
        });
    }
}

我只尝试了POST请求,只是为了清楚地说明我在这里使用GET.需要如何分配复选框值

I tried with POST request only ,just to explain clearly i used GET here. How checkboxes values will be assigned has required

推荐答案

忘记手动从表单中提取所有数据的麻烦.浏览器具有内置工具可以为您完成此任务.

Forget about pulling all the data from the form manually. Browsers have built-in tools to do it for you.

const form = document.querySelector("form");
const formdata = new FormData(form);
$.ajax({
    headers: {"X-CSRFToken": token},
    method: "POST",
    // Pass the form data object to jQuery
    data: formdata,
    // The next two lines stop jQuery trying to convert data and add headers that XHR will do automatically when it is passed a form data object
    processData: false,
    contentType: false,
});

如果您确实非常希望手动进行此操作:

If you really, really, really want to do it manually:

function getChecked(){
    const inputs = document.getElementsByName('mycheckboxes[]');
    const key_values = [];
    for(let i=0; i<inputs.length; i++) {
        let input = inputs[i];
        if (input.type=='checkbox' && input.checked) {
            key_values.push(
                encodeURIComponent(input.name) + 
                "=" +
                encodeURIComponent(input.value)
            );
        }
    }
    const form_encoded_data = key_values.join("&");
    return form_encoded_data;
};

这篇关于如何访问复选框值并将其传递给Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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