在GET ajax调用中传递HEX颜色

I'm trying to pass some hex colours to a php script via an GET ajax call. PHP doesn't seem to like the hex colours though, I've tried replacing the # and using encodeURIComponent neither of which work.

here's the js (with each currentColors entry being a hex color)

var dataString = 'designName=test&mc1='+currentColors[1]+'&mc0='+currentColors[0]+'&sp='+currentColors[2];
var strippedString = encodeURIComponent(dataString);

Use encodeURIComponent to encode URI components:

var strippedString = 
    "designName=test" + 
    "&mc1=" + encodeURIComponent(currentColors[1]) +
    "&mc0=" + encodeURIComponent(currentColors[0]) +
    "&sp="  + encodeURIComponent(currentColors[2]);

Example:

var strippedString = 
    "designName=test" + 
    "&mc1=" + encodeURIComponent("#FF0000") +
    "&mc0=" + encodeURIComponent("#00FF00") +
    "&sp="  + encodeURIComponent("#0000FF");
// "designName=test&mc1=%23FF0000&mc0=%2300FF00&sp=%230000FF"

On the server-side the query string will yield:

// parse_str("designName=test&mc1=%23FF0000&mc0=%2300FF00&sp=%230000FF", $my_GET);
// var_dump($my_GET);

array(4) {
  ["designName"]=>
  string(4) "test"
  ["mc1"]=>
  string(7) "#FF0000"
  ["mc0"]=>
  string(7) "#00FF00"
  ["sp"]=>
  string(7) "#0000FF"
}

You could do this:

var strippedString = dataString.split('#').join('');

Then, server-side, prepend '#' to the parameters again.


.split('#') splits a string up into a array, at the '#' character:

var s = 'designName=test&mc1=#FF0000&mc0=#FFFFFF&sp=#FF00FF';
var a = s.split('#');
console.log(a);
//["designName=test&mc1=", "FF0000&mc0=", "FFFFFF&sp=", "FF00FF"]

.join('') then joins this array together again:

var s = a.join('');
console.log(s);
//'designName=test&mc1=FF0000&mc0=FFFFFF&sp=FF00FF'

You can also use a placeholder / replacement string in the .join(''):

var s = a.join('%');
console.log(s);
//'designName=test&mc1=%FF0000&mc0=%FFFFFF&sp=%FF00FF'

Or, like Salman A answered, use encodeURIComponent on the components only. (which is no doubt faster than array functions like I suggested)