【问题标题】:Serialize form data into array notation将表单数据序列化为数组表示法
【发布时间】:2016-11-12 07:14:41
【问题描述】:

我有这个表格

<form action="" method="post">
  <input type="hidden" name="one" value="somevalue">
  <input type="hidden" name="two" value="anothervalue">
  <input type="hidden" name="three" value="someothervalue">
</form>

我也可以使用 jQuery。

我如何序列化表单数据以获取 $.post()$.ajax() 方法以这种方式在 HTTP 请求中发送数据:

mydata[one]: somevalue
mydata[two]: anothervalue
mydata[three]: someothervalue

代替:

one: somevalue
two: anothervalue
three: someothervalue

【问题讨论】:

    标签: javascript jquery forms http serialization


    【解决方案1】:

    两个建议:

    1) 直接设置名称:

    <input type="hidden" name="mydata[one]" value="somevalue">
    

    2) 加载后更改表单的名称(如果您想要一些动态行为)。类似的东西(未测试):

    $(document).ready(function() {
        var prefix = 'data'; //or get from some data- attribute
        $('form input').each(function() {
            $(this).attr('name', prefix + '[' + $(this).attr('name') + ']' );
        });
    });
    

    然后,如果您想通过 AJAX+jQuery 发送数据,一种方法是使用serialize() 序列化您的表单数据。

    【讨论】:

    • 是的,第二个选择是我最终使用的。我无法修改源 HTML 表单,这就是我需要客户端解决方案的原因。
    【解决方案2】:

    您不能通过$.ajax() 发送数组,但可以发送 JSON 字符串。所以,这样的事情会起作用:

    var frm = $(document.myform);
    var data = JSON.stringify(frm.serializeArray());
    

    例子:

    $.ajax({
        type: "POST",
         url: targetURL,
        data: JSON.stringify($('#form').serializeArray())
    })
    .done(function(data){
          console.log(data);
          return true;
    })
    .complete(function() {})
    .error(function(xhr, textStatus, errorThrown) {
         console.log('ajax loading error...');
         return false;
        }
    });
    

    在 PHP 端,使用 json_decode 将 JSON 转换回数组:

    // decode JSON string to PHP object, 2nd param sets to associative array
    $decoded = json_decode($_REQUEST['data'],true);
    
    output values:
    foreach ($decoded as $value) {
       echo $value["name"] . "=" . $value["value"];
    }
    

    参考资料:

    https://www.sitepoint.com/jquery-php-ajax-json/

    https://stackoverflow.com/a/11338832/1447509

    https://jsfiddle.net/gabrieleromanato/bynaK/

    【讨论】:

    • 酷,我忘了告诉我需要客户端解决方案。 mrlew 指出了正确的方向。无论如何,谢谢。
    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 2013-11-07
    • 2016-12-29
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多