jQuery serialize converts all spaces to plus

爱⌒轻易说出口 提交于 2019-11-27 03:45:23

问题


Currently, everywhere I use serialize I have to use it like this:

.serialize().replace(/\+/g,'%20');

otherwise any spaces in the form data will be coverted to +'s. Is there a setting that can make this the default.


回答1:


For fun, here's an alternative that doesn't use a temporary variable:

$.fn.serializeAndEncode = function() {
    return $.map(this.serializeArray(), function(val) {
        return [val.name, encodeURIComponent(val.value)].join('=');
    }).join('&');
};

$("#formToSerialize").serializeAndEncode();



回答2:


I had to do the same thing. The solution Terry gave, with escape(), doesn't work. The = and & are getting encoded (we don't want that) and the + are still there.

What I did is creating my own function to serialize:

var QueryString = "";
$(selector).each(function(index) {
    if(QueryString != "") QueryString += "&";
    QueryString += $(this).get(0).id + "=" + encodeURIComponent( $(this).val() );
});



回答3:


Don't believe there is a default, you will need to encode the string in one of these ways.

Though you could create your own plugin:

jQuery.fn.serializeAndEncode = function() {
    return escape(this.serialize());
}

$(myForm).serializeAndEncode();


来源:https://stackoverflow.com/questions/11025594/jquery-serialize-converts-all-spaces-to-plus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!