硬编码的URL' s

时间:2016-09-08 07:48:11

标签: javascript jquery url hardcode

我对硬编码网址有疑问。使用jquery从JavaScript进行调用时,我将其作为$.post('http://localhost:8000/timer/check/'

现在这在我的开发服务器上工作正常。当我必须在另一台服务器上部署它时,我必须手动更改代码中的所有url。那么如何避免硬编码网址呢?

3 个答案:

答案 0 :(得分:2)

为实现此目的,您必须在元标记

中使用以下标记
<head>
<base href="{{your base url_here}}">
</head>

在此之后,您必须编写相对于此基本URL的路径。

例如

<head>
    <base href="http://localhost:8000/timer/check/">
</head>

如果完整网址为http://localhost:8000/timer/check/test.php。现在,您可以在ajax调用中相对于基本URL 'test.php'进行编写。

示例:https://jsfiddle.net/ptLzs7m5/1/

答案 1 :(得分:1)

试试这个

 var host = window.location.hostname;
 var url = host + "/" + timer/check/;

现在您可以将网址传递给帖子方法

您也可以使用

 window.location.protocol   //you'll get your protocol `http` or `https` 
 window.location.port       //this will return the port

答案 2 :(得分:0)

这个常见问题有一些解决方案 -

1)使用$.post('./timer/check')。这将采用当前域并附加网址(推荐)

2)创建一个全局变量并在任何地方使用它。在处理dev时分配本地URL并在处理生产时分配prod url。

3)创建一个包装器并始终使用该包装器发送请求。使用当前状态(Dev或Prod)创建一个全局变量作为其值并不断更改它。并使用它像这样 -

post(url) {
    var baseurl = '';
    if(CURRENT_ENVIRONMENT=='DEV')
        baseurl = 'http://localhost:8080';
    else if(CURRENT_ENVIRONMENT=='PROD')
        baseurl = 'http://yourwebsiteurl';'
    $.post(baseurl+'/timer/check')
         //and so on
}

您可以根据自己的喜好使用。