【问题标题】:Using jQuery, how do I way attach a string array as a http parameter to a http request?使用 jQuery,我如何将字符串数组作为 http 参数附加到 http 请求?
【发布时间】:2010-06-01 15:18:05
【问题描述】:

我有一个请求映射如下的spring控制器

@RequestMapping("/downloadSelected")
public void downloadSelected(@RequestParam String[] ids) {
    // retrieve the file and write it to the http response outputstream
}

我有一个对象的 html 表,其中每一行都有一个复选框,其中对象的 id 作为值。当他们提交时,我有一个 jQuery 回调来序列化所有 id。我想将这些 id 粘贴到一个名为“ids”的 http 请求参数中,以便我可以轻松获取它们。

我想我可以做到以下几点

var ids = $("#downloadall").serializeArray();

然后我需要获取每个 id 并将它们添加到名为 ids 的请求参数中。但是有没有一种“标准”的方式来做到这一点?喜欢用jQuery吗?

【问题讨论】:

    标签: java jquery arrays spring-mvc httprequest


    【解决方案1】:

    我不知道“标准方式”,但我会这样做。

    var ids = $("#downloadall").serializeArray();
    

    将在表单上为您提供数据集(仅显示选中的项目):

    [{name:"foo1", value:"bar1"}, {name:"foo2", value:"bar2"}]
    

    要将它提供给 jQuery 的 .ajax() 只需:

    $.ajax({
      url: <your url>,
      data: ids.map(function (i) {return i.name+'='+i.value;}).join('&')
    });
    

    Array.map() 尚不兼容所有浏览器,因此您最好在页面上也包含此代码:

    if (!Array.prototype.map) {
      Array.prototype.map = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function")
          throw new TypeError();
    
        var res = new Array(len);
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
          if (i in this)
            res[i] = fun.call(thisp, this[i], i, this);
        }
        return res;
      };
    }
    

    我从mozilla developer center得到这个代码sn-p。

    我没有将它们放在?ids=... 参数中,但是这样它们很容易在服务器端访问。您可以随时修改地图功能以满足您的需求。

    【讨论】:

    • 是的,这也是个好主意!我喜欢 jQuery,它们似乎总是有你需要的东西 :)
    猜你喜欢
    • 1970-01-01
    • 2011-07-29
    • 2017-04-30
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2018-09-04
    相关资源
    最近更新 更多