Naish O'Loughlin
Naish O'Loughlin

Reputation: 59

Why does string not pass correctly to server when there is a '#' in my variable?

I am attempting to stringify an object but my url does not return correctly when there is a '#` in the object.

I've outputted the value of JSON.stringify($scope.parameter); and it is correct however the url is not.

$scope.parameter = '#' + parameter;

var url = $scope.url + '&functions=' + JSON.stringify($scope.parameter);

I expect it to be {"1":"i001::#11 object"}

but its actually {"1":"i001::

Upvotes: 1

Views: 44

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075079

Because you're not encoding it correctly, so it's being interpreted as a fragment identifier (the # introduces a fragment identifier).

You must URI-encode things you put in URIs:

var url = $scope.url + '&functions=' + encodeURIComponent(JSON.stringify($scope.parameter));
// ------------------------------------^

Technically, you have to URI-encode functions in the above as well, but since the URI-encoded version of functions is, er, functions, I didn't bother above. But if it weren't necessarily safe, then:

var url = $scope.url + '&' + encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify($scope.parameter));

If the names you use in name=value pairs only have digits, letters, underscores, and dashes in them, you can safely omit the URI-encoding for them as I did in the first example above. (There are some other chars that are allowed too, but if you start getting into using those, just encode as in the second example for safety.)

Upvotes: 3

Related Questions