jQuery使用变量组合URL

jQuery combining URL using a variable

本文关键字:组合 URL 变量 jQuery      更新时间:2023-09-26

上传至托管服务器后,以下代码成功转为http://myexample.com/otherpartsofpath:

 ajax: {
        url: 'http://' + window.location.hostname + '/otherpartsofpath', 
        type: 'GET',
        ...

但是当在本地计算机上渲染时,它会给出一个错误。这就是为什么在这个例子中,我应该显式定义URL:

 ajax: {
        url: 'http://localhost:10930/otherpartsofpath', 
        type: 'GET',
        ...

如何使代码在没有明确定义URL的情况下在本地工作?

使用相对路径/test将始终产生正确的协议、主机名和端口。因此,为了方便起见,您总是可以使用:

 ajax: {
        url: '/otherpartsofpath', 
        type: 'GET',
        ...

http://test.com/directory/test.html上运行时为http://test.com/otherpartsofpath .

http://localhost:1234/directory/test.html上运行时,它是http://localhost:1234/otherpartsofpath .

出于安全考虑,你不能。

使用本地服务器进行测试。如果要从远程服务器获取数据,请设置代理

如果你不在本地80端口上你就必须这样做

var hostName = window.location.hostname;
if ( window.location.port != '') {
    hostName += ':' + window.location.port;
}