如何使用Javascript

时间:2019-05-03 10:57:57

标签: javascript mysql laravel axios

我的laravel应用程序中有一堆复选框,我想将它们另存为数组,保存在MySQL数据库中,但是我不确定该怎么做。

这是我的输入字段:

<input type="checkbox" class="form-check-input" name="vehicle[]" value="bmw">BMW
<input type="checkbox" class="form-check-input" name="vehicle[]" value="audi">Audi
<input type="checkbox" class="form-check-input" name="vehicle[]" value="mercedes">Mercedes
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chrysler">Chrysler
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chevrolet">Chevrolet
<input type="checkbox" class="form-check-input" name="vehicle[]" value="ford">Ford

对于简单的输入字段,我在.js文件中执行此操作:

var formData = new FormData();
    formData.append(
        "name",
        $("#uploadModal")
            .find('input[name="name"]')
            .val()
    );
// etc. etc,

,然后我使用axios提交数据:

 axios.post($("#uploadModal form").attr("action"), formData) ...

如何将选中的checkbox数组添加到formData?

1 个答案:

答案 0 :(得分:1)

<input type="checkbox" class="form-check-input" name="vehicle[]" value="bmw">BMW
<input type="checkbox" class="form-check-input" name="vehicle[]" value="audi">Audi
<input type="checkbox" class="form-check-input" name="vehicle[]" value="mercedes">Mercedes
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chrysler">Chrysler
<input type="checkbox" class="form-check-input" name="vehicle[]" value="chevrolet">Chevrolet
<input type="checkbox" class="form-check-input" name="vehicle[]" value="ford">Ford

<script>
function sendCall(){
    var formData = new FormData();
    var vehicleList = [];
    $("[name='vehicle[]']").each(function(){
       if($(this).is(":checked")){
           vehicleList.push($(this).val());
       }
    });

    formData.append("vehicle",vehicleList);

---> add axios request with formData object
}

--> call sendCall on click btn
</script>