Jquery将值作为查询字符串附加到url

时间:2013-12-05 12:21:58

标签: javascript jquery

我尝试了一些jquery将我的复选框选中的值附加到url作为查询字符串代码工作得很好但是当我检查多个复选框时,url会喜欢这个......

Localhost:355/searchdatabase/?manufacturer=LG&manufacturer=Samsung&manufacturer=Test

但我需要网址赞

Localhost:355/searchdatabase/?manufacturer=LG,Samsung,Test

这是我的代码

$(document).ready(function () {
    $('input[type="checkbox"]').on('change', function (e) {
        var data = [],
            loc = $('<a>', { href: window.location })[0];
        $('input[type="checkbox"]').each(function (i) {
            if (this.checked) {
                data.push(this.name + '=' + this.value);
            }
        });
        data = data.join('&');

        $.post('/ajax-post-url/', data);
        if (history.pushState) {
            history.pushState(null, null, loc.pathname + '?' + data);
        }
    });
});

我的复选框列表将代码分组

          <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>LG</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>Samsung</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>Test</label>
        </div>




         <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>iron</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>steel</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>copper</label>
        </div>

我需要制造商作为一个团体和材料作为另一个..

1 个答案:

答案 0 :(得分:1)

您可以将所有制造商添加到分离的数组中,然后添加为一个字段。

var manufacturers = [];
if (this.checked) {
    if (this.name === 'manufacturers') {
        manufacturers.push(this.value);
    } else {
        data.push(this.name + '=' + this.value);
    }
}

data = data.join('&');之前添加data.push('manufacturers=' + manufacturers.join(','));