用url作为查询字符串附加复选框选择的值 [英] Append the checkbox selected values with url as querystring

查看:73
本文介绍了用url作为查询字符串附加复选框选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的页面中,我有一些复选框.我需要将检查后的值作为查询字符串通过url传递. 这是我的复选框代码

In my page I have some checkboxes.I need to pass the checked values through url as query string. here is my checkbox code

 <div class="panel-body">
                <div class="rowElem">
                  <input type="checkbox" name="chbox" id="">
                  <label>Color #1</label>
                </div>
                <div class="rowElem">
                  <input type="checkbox" name="chbox" id="">
                  <label>Color #2</label>
                </div>
                <div class="rowElem">
                  <input type="checkbox" name="chbox" id="">
                  <label>Color #3</label>
                </div>
              </div>

我的初始网址就像www.test.com 如果我检查#3的颜色,则该网址将类似于www.test.com/?color=color#3

my initial url is like www.test.com if I check the color #3 then the url will look like www.test.com/?color=color #3

如何使用ajax完成此操作.?

How to done this using ajax.???

推荐答案

尝试一下.在每个复选框上,将帖子更改为发布到服务器,并将HTML5 pushState包含数据的URL更改为

Try this. On each checkbox change post to the server and html5 pushState the URL with the data.

$('input[type="checkbox"]').on('change', function(e){
    var data = $('input[type="checkbox"]').serialize(),
        loc = $('<a>', {href:window.location})[0];
    $.post('/ajax-post-url/', data);
    if(history.pushState){
        history.pushState(null, null, loc.pathname+'?'+data);
    }
});

通过在末尾添加索引来更新以使用相同的命名输入.

Updated to work with same named inputs by adding the index to the end.

$('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+i+'='+this.value);
    }
    });
    data = data.join('&');

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

已更新为以逗号分隔的列表形式工作. key=a,b,c,d,e.

Updated to work as comma separated list. key=a,b,c,d,e.

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

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

这篇关于用url作为查询字符串附加复选框选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆