【问题标题】:Sending a serialized data from js to server side in a variable在变量中将序列化数据从 js 发送到服务器端
【发布时间】:2012-11-23 13:11:22
【问题描述】:

我正在尝试通过 url 中的查询字符串/变量发送序列化数据。如您所知,当我们在 js 中进行序列化时,它会自己构建一个查询字符串。我正在将此数据发送到用 django 编写的服务器端。我该怎么做或如何在 django 代码中收集数据。

这就是我正在做的。

selected = $('input:checkbox:checked').serialize();

这给了我multiselect_select_month=10&multiselect_select_month=11&multiselect_select_month=05的结果

我想在一个带有其他变量的 url 中发送它,并将孔字符串 (multiselect_select_month=10&multiselect_select_month=11&) 收集到一个变量中。 像

serialized = 'multiselect_select_month=10&multiselect_select_month=11'

在服务器端我正在写serialized = request.GET.get('serialized', '')

如何在单个变量中发送该序列化字符串(这是一个查询字符串),以便我可以在服务器端捕获它。

注意:我还想用上面的序列化数据发送其他变量。

【问题讨论】:

  • 那么,您的问题到底是什么?
  • 我的问题是如何在单个变量中发送该序列化字符串(这是一个查询字符串),以便我可以在服务器端捕获它。
  • 只需将其作为参数附加到您的 HTTP GET / 链接 / 但是您正在联系服务器:"htpp://some.request.com/?" + serialized
  • 是的,我试过这个,但它只给了我第一个'multiselect_select_month'。我需要一个变量中的所有“multiselect_select_month”,并且不知道它可能包含多少个“multiselect_select_month”。
  • 啊,我明白了。每个multiselect_select_month 都会覆盖它之前的那个。我看看能不能给个答案。

标签: javascript python django serialization query-string


【解决方案1】:

您需要对 serialized 进行 URL 编码,然后您可以将其发送到单个变量中。

serialized = encodeURIComponent(serialized);
var link = "http://host.com/?data=" + serialized;

【讨论】:

    【解决方案2】:

    此代码将所有 multiselect_select_month 值连接到 1 个参数中。
    (还有显着减少参数长度的额外好处)

    var multiSelects = [];
    $('input:checkbox:checked').each(function(){
        multiSelects.push(this.value);
    });
    var parameter = "?multiselect_select_month=" + multiSelects.join(',');
    //Will return "?multiselect_select_month=10,11,05" instead of "multiselect_select_month=10&multiselect_select_month=11&multiselect_select_month=05"
    

    然后您可以在服务器端获取ultiselect_select_month 参数,并在',' 上获取explode

    string.split('10,11,05', ',')
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2015-05-23
      • 1970-01-01
      • 2022-01-23
      • 2013-04-11
      • 2021-12-07
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多