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

前端 未结 5 626
自闭症患者
自闭症患者 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:10

    2020 Update

    Use encodeURIComponent, an example pulled from MDN.

    // encodes characters such as ?,=,/,&,:
    console.log(encodeURIComponent('?x=шеллы'));
    // expected output: "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
    
    console.log(encodeURIComponent('?x=test'));
    // expected output: "%3Fx%3Dtest"
    

    encodeURI which expects a complete URI could be worth a look as well.

    My previous suggestion was to use escape() method, but now that it has been deprecated and soon will be dropped as well.

    Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code

    More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape

提交回复
热议问题