【问题标题】:attach jquery array to form submit将 jquery 数组附加到表单提交
【发布时间】:2014-02-08 04:05:48
【问题描述】:

我正在使用以下内容在按钮单击时提交表单。我还需要在这篇文章中附加一个名为“selected”的数组。我不能为此使用 ajax,因为发布页面上会进行下载。我需要这个数组来处理要下载的文件。

我做了一些搜索并发现了这个,但也无法让它工作:

var input = $("<input>").attr({"type":"hidden","name":"selected"}).val(selected);
$('#test').append(input);

当前:

var selected = [1,2,54,56,23]; // could be anything

$('#test').submit(function(event) {
    if (selected.length > 0)
    {
        $('#test').attr('action','/process/p_screenshots_download2.php');
        $('#test').attr('type','post');
        return;
    }
    event.preventDefault();
});

【问题讨论】:

    标签: jquery post form-submit onsubmit


    【解决方案1】:

    试试

    $('#test').submit(function(event) {
        $.each(selected, function(i, v){
            var input = $("<input>").attr({"type":"hidden","name":"selected[]"}).val(v);
            $('#test').append(input);    
        });
        if (selected.length > 0)
        {
            $('#test').prop('action','/process/p_screenshots_download2.php');
            $('#test').prop('method','POST');
            return;
        }
        event.preventDefault();
    });
    

    这将在表单提交之前将一组隐藏输入与数组中的值添加到表单中。

    【讨论】:

    • 似乎也不起作用...我得到了一些类似于 ...php?selected[]=1609449&selected[]=4697 并执行 var_dump( $_POST['selected' ]);返回 NULL。
    • @user756659 您的表单的操作是什么?是GET 还是POST
    • $('#test').attr('type','post');
    • 刚刚意识到问题所在 - $('#test').attr('method','post');现在似乎工作正常。
    • @user756659 使用 prop 而不是 attr $('#test').prop('method','POST'); 或将其设置为在 html 中发布。
    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2013-04-18
    • 2020-05-20
    相关资源
    最近更新 更多