1

I'm using an API that needs a URL like this one:

var URL_PARADAS = 'http://datos.santander.es/api/rest/datasets/paradas_bus.json';

function paradas(lat, lon, dist) {
  console.log(lat);
  console.log(lon);

  var lat_min = lat - dist;
  var lat_max = lat + dist;

  var lon_min = lon - dist;
  var lon_max = lon + dist;

  var xmlHttp = null;
  xmlHttp = new XMLHttpRequest();

  xmlHttp.open('GET', URL_PARADAS + '?query=wgs84_pos\:lat:{' + lat_min + '%20TO%20' + lat_max + '}'
                                  + '%20AND%20'
                                  + 'wgs84_pos\:long:{' + lon_max + '%20TO%20' + lon_min + '}',
  false);
  xmlHttp.send(null);

  var result = JSON.parse(xmlHttp.responseText);
  console.log(result);
}

working url

Without slash: on the URL it won't work, if I use xmlHttp.open(url) it's replaced by : so it doesn't receive anything.

Edit: I needed to replace \ to "slash" on this question due to bad output.

Kenny
  • 1,110
  • 3
  • 13
  • 42
  • http://stackoverflow.com/questions/332872/how-to-encode-a-url-in-javascript?rq=1 – Niloct Aug 23 '14 at 22:55
  • @Niloct Nope, encoded it will be : or %3A, so it doesn't output anything then. – Kenny Aug 23 '14 at 22:56
  • Please show your code. – Ry- Aug 23 '14 at 23:00
  • @minitech added. Also I added a working URL and noticed that the encoding function from the page gave me the answer. I tried to encode my self this and didn't work. Thanks. – Kenny Aug 23 '14 at 23:05

1 Answers1

2

JavaScript string literals interpret escape sequences. If a backslash isn’t followed by a valid escape sequence, it is removed. Escape your backslashes, and they’ll be put in the URL:

  xmlHttp.open('GET', URL_PARADAS + '?query=wgs84_pos\\:lat:{' + lat_min + '%20TO%20' + lat_max + '}'
                                  + '%20AND%20'
                                  + 'wgs84_pos\\:long:{' + lon_max + '%20TO%20' + lon_min + '}',
Ry-
  • 218,210
  • 55
  • 464
  • 476