簡體   English   中英

通過表單將javascript / jquery數組傳遞給php

[英]Passing javascript/Jquery array to php through a form

因此,我有一個jquery函數,用於檢查選中了哪些復選框,並將ID放入數組中。 現在,該數組將傳遞給隱藏輸入字段的值,然后提交給php腳本。 發生的情況是,看起來每個值都放在第一個索引中,而不是單個索引中。

這是獲取數組中選中復選框的ID的功能。 我讀到有關push的信息,到目前為止,我了解push實際上將值推入了新索引嗎?

$(".article-checkbox:checked").each(function() {
            multipleCheckboxes.push($(this).val());
        });

我的表格:

<form id="publish-form" method="post" action="publisharticle.php" onsubmit="getMultipleCheckboxValues()">
    <input type="hidden" value="" name="checkbox-value2[]" id="checkbox-value2">
    li><input type="submit" value="Publish"></li>
</form>

函數onsubmit:

function getMultipleCheckboxValues(){
    getValueUsingClass();
    $("#checkbox-value2").val(multipleCheckboxes);
}

function getValueUsingClass(){
        /* declare an checkbox array */
        var chkArray = [];
        var i = 0;

        /* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
        $(".article-checkbox:checked").each(function() {
            chkArray.push($(this).val());
            multipleCheckboxes.push($(this).val());
            i++;
        });

        /* we join the array separated by the comma */
        var selectedOne = chkArray[0];
        var selected;
        selected = chkArray.join(',') + ",";

        /* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
        if(selected.length > 1){
            oneCheckbox = selectedOne;
        //alert("Please at least one of the checkbox" + selectedCheckboxes); 
    }else{
        alert("Please at least one of the checkbox");   
    }
}

和PHP:

$checks =  $_POST['checkbox-value2'];

echo $checks[0];

現在在PHP中,我想遍歷數組而不是字符串。 可以說,即使我選擇了索引0,我也選中了復選框1和2上面echo 1,2的php代碼。我也嘗試了:

var i = 0;
$(".article-checkbox:checked").each(function() {
            chkArray.push($(this).val());
            multipleCheckboxes[i].push($(this).val());
            i++;
        });

將表單數據作為鍵=>值提交到PHP腳本的一種更好的方法。

HTML

<form id="publish-form" method="post">
    <input type="checkbox" id="checkbox1"> Checkbox1
    <input type="checkbox" id="checkbox2"> Checkbox2
     <input type="checkbox" id="checkbox3"> Checkbox3
    <button>Submit</button>
</form>

JavaScript的

var items = {};

$('button').click(function () {
    $('#public-form input').each(function () {
        if ($(this).prop('checked')) {
            items[$(this).id] = $(this).val();
        }
    });

    $.post('/publisharticle.php', items).done(function (data) {
        // response from php script
        console.log(data);
    });

});

PHP

foreach($_POST as $key => $value){
    echo $key . ": " . $value . "\n";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM