Escape all special characters in a string that is sent by jquery ajax

前端 未结 5 632
自闭症患者
自闭症患者 2020-12-14 08:39

I am trying to send text in key value pairs while doing a contentType: \"application/json; charset=utf-8\", ajax post to a web service. The problem I am facing

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 09:06

    1. Do not use escape(). Source: MDN escape() Documentation...

    Programmers should not use or assume the existence of these features and behaviours...

    1. Do not use encodeURI(). (Alternative listed below.) Source: MDN encodeURI() Documentation...

    If one wishes to follow the more recent RFC3986 for URLs... the following code snippet may help:

    function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

    1. Do not use encodeURIComponent(). (Alternative listed below.) Source: MDN encodeURIComponent() Documentation...

    To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

    function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

    So, if you want to encode all data except for these operators: +@?=:#;,$&, use fixedEncodeURI(). If you want to include those characters (which are used in defining GET parameters, and other uses), then use fixedEncodeURIComponent().

提交回复
热议问题