0

I've got a JQuery function using getJSON to bring some userifo. It's like that:

$.getJSON("http://server.com/?apirequested=userinfo", function(data){
   ...
   ...
});

This works fine, but I'm trying to change it to use same code for several servers using relatives url's.

I'm trying several things like:

$.getJSON($(location).attr('hostname')+"/?apirequested=userinfo" ...

or

$.getJSON($(location).attr('protocol')+$(location).attr('hostname')+"/?apirequested=userinfo",

or

$.getJSON(location.hostame+"/?apirequested=userinfo" ...

But it does not work. What am I doing wrong?

Any suggestions?

Thanks in advance for your time.

Manolo
  • 78
  • 1
  • 8
  • 1
    Have you read any documentation for [`location`](https://developer.mozilla.org/en-US/docs/Web/API/Location)? – David Thomas Mar 21 '18 at 17:50
  • **…accessible via Document.location and Window.location respectively…**. By the way, `location` interface has nothing to do with jQuery. – Stphane Mar 21 '18 at 17:53
  • why doesn't `$.getJSON(location.host+"/?apirequested=userinfo"` work? – CumminUp07 Mar 21 '18 at 17:57

3 Answers3

4

This might be help you.

http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

$(location).attr('host');                        www.test.com:8082
$(location).attr('hostname');                    www.test.com
$(location).attr('port');                        8082
$(location).attr('protocol');                    http:
$(location).attr('pathname');                    index.php
$(location).attr('href');                        http://www.test.com:8082/index.php#tab2
$(location).attr('hash');                       #tab2
$(location).attr('search');                     ?foo=123
1

I found the problem. It works with:

$.getJSON($(location).attr('protocol')+"//"+$(location).attr('hostname')+"/?apirequested=userinfo", ...
Manolo
  • 78
  • 1
  • 8
0
let myurl = location.protocol+"//"+location.hostname+"/?apirequested=userinfo";
$.getJSON(myurl);

or perhaps simpler

let myurl = location.origin + "/?apirequested=userinfo";
$.getJSON(myurl);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100