6

我有一个关于硬编码网址的查询。当使用 jquery 从 JavaScript 进行 post 调用时,我这样做 $.post('http://localhost:8000/timer/check/'

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

4

3 回答 3

3

为此,您必须在元标记中使用以下标记

<head>
<base href="{{your base url_here}}">
</head>

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

例如

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

如果完整的 URL 是http://localhost:8000/timer/check/test.php. 'test.php'现在您可以在 ajax 调用中相对于基本 url 编写。

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

于 2016-09-08T07:57:44.283 回答
1

试试这样

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

现在您可以将 url 传递给您的 post 方法

你也可以用这个

 window.location.protocol   //you'll get your protocol `http` or `https` 
 window.location.port       //this will return the port
于 2016-09-08T07:58:52.587 回答
0

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

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

2)创建一个全局变量并在任何你想要的地方使用它。在开发时分配本地 url,在生产时分配产品 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
}

你可以使用任何你喜欢的。

于 2016-09-08T08:01:37.737 回答