1

In a web app, I'm sending content of a XML file as part of the URL parameter (not the best design probably but for now I'm stuck with it). So the address looks like this:

http://localhost:5000/fill?xml=XXXXXXXXXXXXX

which is generated with url_for('url', xml=xml) from Flask.

And I'm doing this on the client side:

  var img = document.getElementById('preview');
  var xmlstr = decodeURIComponent(GetURLParameter("xml"));
  var xml = $.parseXML(xmlstr);

Naturally the content of the XML file will get encoded. But all the spaces in the file is transformed into plus signs +. And when I use $.parseXML() function to decode it, the + is still there.

Why?

lang2
  • 11,433
  • 18
  • 83
  • 133

4 Answers4

4

Yes, when you put data in the query string it is URL encoded; converting spaces to + is normal; query parameters are encoded using the application/x-www-form-urlencoded form.

decodeURIComponent() doesn't handle that one difference; simply use .replace() to replace the + characters with spaces first:

var xmlstr = decodeURIComponent(GetURLParameter("xml").replace(/\+/g, " "));

See How can I get query string values in JavaScript?

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

In 2020 I would recommend using the native implementation of URLSearchParams to handle this legacy encoding issue. It is currently supported by basically every browser (except IE, as usual), and NodeJS since v10 (see here).

Simply do:

let myUrl = new URL("http://my.url.here?with=query&xml=...");
let xmlStr = (new URLSearchParams(myUrl.search)).get("xml");

All the encoding and decoding is handled for you.

See documentation here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

cyqsimon
  • 2,752
  • 2
  • 17
  • 38
1

A word of warning to anyone who wants to encode lots of data in the URL: Most proxies, webservers and some browsers have length limits for URLs, and very often they just truncate the URL when that limit is exceeded. The realistic limit is 2000 characters, which should work fine on everything.

0

I would encode XML for url first:

http://localhost:5000/fill?xml=encodeURIComponent(XXXXXXXXXXXXX)

and on the other side decode it before parse xml:

decodeURIComponent()
Lisak
  • 19
  • 2
  • Flask already encodes URL parameters (and is doing so in Python, not JavaScript), which is why the OP is seeing those `+` characters in the first place. `decodeURIComponent()` doesn't handle the difference between a query parameter and a path component. – Martijn Pieters Jul 28 '15 at 08:44