开发者

jQuery form plugin: field value serialization

开发者 https://www.devze.com 2023-02-03 17:27 出处:网络
I\'m used to send passing data with the jQuery form pluging using data: $(\"form#myform\").serialize(). It doesn\'t make sense to开发者_如何学Go create separate forms in my current case, since there a

I'm used to send passing data with the jQuery form pluging using data: $("form#myform").serialize(). It doesn't make sense to开发者_如何学Go create separate forms in my current case, since there are only two fields. Hence I created the following function:

function storeNotificationMessage(name) {
    var content = $("textarea#" + name).val();
    var id = $('#id').val();

    content = encodeURI(content); // tried this
    content = escape(content);    // and that

    $.ajax({
        async: false,
        data: "entry=" + id + "&name=" + name + "&msg=" + msg,
        type: 'post',
        url: '?url=updateEntry',
        success: function(response) {
            done();
        }
    });
}

Unfortunately neither encodeURI nor escape work correctly for special characters like ' or + or German umlauts.

Question: what is the proper way to encode text values?


Don't use escape nor encodeURI nor + when dealing with urls. Simply leave all encoding to jquery:

function storeNotificationMessage(name) {
    $.ajax({
        async: false,
        data: { 
            entry: $('#id').val(), 
            name: name, 
            msg: $('textarea#' + name).val() 
        },
        type: 'post',
        url: '?url=updateEntry',
        success: function(response) {
            done();
        }
    });
}

Remark: using AJAX with async = false makes very little sense and should be avoided.

0

精彩评论

暂无评论...
验证码 换一张
取 消