How to prepare encoded POST data on javascript?

I need to send data by POST method.

For example, I have the string "bla&bla&bla". I tried using encodeURI and got "bla&bla&bla" as the result. I need to replace "&" with something correct for this example.

What kind of method should I call to prepare correct POST data?

UPDATED:

I need to convert only charachters which may broke POST request. Only them.


>>> encodeURI("bla&bla&bla")

"bla&bla&bla"

>>> encodeURIComponent("bla&bla&bla")

"bla%26bla%26bla"

You can also use escape() function.The escape() function encodes a string. This function makes a string portable, so it can be transmitted across any network to any computer that supports ASCII characters.This function encodes special characters, with the exception of: * @ - _ + . / * @ - _ + . /

var queryStr = "bla&bla&bla";
alert(queryStr);               //bla&bla&bla
alert(escape(queryStr));       //bla%26bla%26bla

Use unescape() to decode a string.

var newQueryStr=escape(queryStr);
alert(unescape(newQueryStr));   //bla&bla&bla

Note:

    escape() will not encode: @*/+

    encodeURI() will not encode: ~!@#$&*()=:/,;?+'

    encodeURIComponent() will not encode: ~!*()'

After some search on internet, I got the following:

escape()

Don't use it.

encodeURI()

Use encodeURI when you want a working URL. Make this call:

encodeURI("http://www.google.com/a file with spaces.html")

to get:

http://www.google.com/a%20file%20with%20spaces.html

Don't call encodeURIComponent since it would destroy the URL and return

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")

Then you may create the URL you need:

url = "http://domain.com/?param1=" + param1 + "&param2=99";

And you will get this complete URL:

http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55¶m2=99

Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).

REF:When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Also, as you are using JQuery , take a look at this built-in function.


Use encodeURIComponent() as encodeURI() will not encode: ~!@#$&*()=:/,;?+'

This has been explained quite well at the following link:

http://xkr.us/articles/javascript/encode-compare/

链接地址: http://www.djcxy.com/p/22152.html

上一篇: Web API模型绑定与多部分formdata

下一篇: 如何在JavaScript上准备编码的POST数据?