Javascript Ajax调用中的相对路径问题

MDV*_*000 17 javascript relative-path

好的,我有一个包含以下功能的JavaScript文件:

function AskReason() {
    var answer = prompt("Please enter a reason for this action:", "");
    if (answer != null)
        DoReason(answer);
}

function createXMLHttpRequest() {
    try {
        return new XMLHttpRequest();
    }
    catch (e)
    { alert('XMLHttpRequest not working'); }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    { alert('Msxml2.XMLHTT not working'); }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    { alert('Microsoft.XMLHTTP not working'); }
    alert("XMLHttpRequest not supported");
    return null;
}

function DoReason(reason) {
    var xmlHttpReq = createXMLHttpRequest();
    var url = "/Shared/AskReason.ashx?REASON=" + reason;
    xmlHttpReq.open("GET", url, true);
    xmlHttpReq.send(null);
}
Run Code Online (Sandbox Code Playgroud)

这一行:

    var url = "/Shared/AskReason.ashx?REASON=" + reason;
Run Code Online (Sandbox Code Playgroud)

是什么导致了这个问题.

在VS 2010中调试应用程序 - 此调用适用于我的ashx处理程序.

当我将项目移动到虚拟目录时 - 例如 http://localhost/myapp

此代码将中断,我必须将javascript更改为:

var url = "http://localhost/myapp/Shared/AskReason.ashx?REASON=" + reason;

有关如何解决此问题以便在两种环境中工作的任何想法,或者只是在我将应用程序部署到服务器时接受手动更改?

谢谢,迈克

T.J*_*der 22

Pointy的方式有效,但您必须事先知道要部署它的位置.

或者,只是不要使用以下命令启动相对路径/:

var url = "Shared/AskReason.ashx?REASON=" + reason;
Run Code Online (Sandbox Code Playgroud)

这将相对于当前文档的位置得到解决.因此,如果当前文件是:

http://localhost/myapp/index.aspx
Run Code Online (Sandbox Code Playgroud)

......那将解决

http://localhost/myapp/Shared/AskReason.ashx?REASON=foo
Run Code Online (Sandbox Code Playgroud)

  • @ MDV2000:您仍然可以在结构中使用相对路径.例如,如果源是`http:// localhost/myapp/subfolder/index.aspx`,你可以使用`../ Shared/AskReason.ashx`来访问`http:// localhost/myapp/Shared/AskReason.ashx`.多个`../../`也很好.我建议保持应用程序内的所有路径相对而不是"根". (6认同)

Poi*_*nty 6

以"/"(并且没有协议和主机)开头的路径相对于主机的.如果您部署的应用程序位于"http:// whatever/myapp",那么您的根相对路径必须以"/ myapp"开头.

当您在涉及某种页面模板机制的服务器端环境中工作时,一个常见的技巧是让路径的这一部分成为某种配置变量,以便您可以编写具有以下路径的页面:

<a href='${root}/something/something'>click me</a>
Run Code Online (Sandbox Code Playgroud)

然后根据配置将"root"变量扩展为"/ myapp"或其他.