【问题标题】:Get hostname in JQuery [duplicate]在JQuery中获取主机名[重复]
【发布时间】:2018-03-21 17:47:00
【问题描述】:

我有一个使用 getJSON 的 JQuery 函数来带来一些 userifo。是这样的:

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

这很好用,但我正在尝试将其更改为使用亲戚网址的多个服务器使用相同的代码。

我正在尝试几件事,例如:

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

或

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

或

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

但它不起作用。我做错了什么?

有什么建议吗?

提前感谢您的宝贵时间。

【问题讨论】:

  • 你读过location的任何文档吗?
  • …可分别通过 Document.location 和 Window.location 访问…。顺便说一句,location 接口与jQuery无关。
  • 为什么$.getJSON(location.host+"/?apirequested=userinfo" 不起作用?

标签: javascript jquery getjson hostname


【解决方案1】:

这可能会对你有所帮助。

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

【讨论】:

    【解决方案2】:

    我发现了问题。它适用于:

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

    【讨论】:

    • 为什么不直接使用location.protocol 和location.hostname 呢?
    【解决方案3】:
    let myurl = location.protocol+"//"+location.hostname+"/?apirequested=userinfo";
    $.getJSON(myurl);
    

    或者更简单

    let myurl = location.origin + "/?apirequested=userinfo";
    $.getJSON(myurl);
    

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2014-10-24
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多