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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5092352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:37:33  来源:igfitidea点击:

Relative Path Problems in Javascript Ajax call

javascriptrelative-path

提问by MDV2000

Okay, I have a JavaScript file with the following functions:

好的,我有一个具有以下功能的 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);
}

This line:

这一行:

    var url = "/Shared/AskReason.ashx?REASON=" + reason;

Is what is causing the problem.

是什么导致了问题。

In VS 2010 debugging the app - this call works to my ashx handler.

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

When I move the project to a virtual directory - example http://localhost/myapp

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

this code will break and I have to change the javascript to this:

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

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

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

Any ideas on how I can fix this to work in both environments or just accept the manual change when I deploy apps to servers?

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

Thanks, Mike

谢谢,迈克

回答by T.J. Crowder

Pointy's wayworks, but you have to know in advance where you're going to deploy it.

Pointy 的方式有效,但您必须提前知道将在哪里部署它。

Alternately, simply don't start the relative path with a /:

或者,简单地不要用 a 开始相对路径/

var url = "Shared/AskReason.ashx?REASON=" + reason;

That will be resolved relative to the current document's location. So if the current document is:

这将相对于当前文档的位置进行解析。所以如果当前文档是:

http://localhost/myapp/index.aspx

...then that will resolve to

...然后将解决

http://localhost/myapp/Shared/AskReason.ashx?REASON=foo

回答by Pointy

Paths that start with a "/" (and no protocol & host) are relative to the rootof the host. If you deploy such that your application is at "http://whatever/myapp", then your root-relative paths have to start with "/myapp".

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

When you're working in a server-side environment that involves some sort of page template mechanism, a common trick is to have that part of the path be some kind of configuration variable so that you can write pages with paths like:

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

<a href='${root}/something/something'>click me</a>

Then that "root" variable is expanded based on configuration to "/myapp" or whatever.

然后根据配置将“root”变量扩展为“/myapp”或其他任何内容。

回答by chromaloop

I had a similar problem where an absolute URL was needed but the reference broke when going from localhost to the production server. I resolved it by checking if a "localhost" string exists in:

我有一个类似的问题,需要一个绝对 URL,但是从 localhost 到生产服务器时引用中断了。我通过检查“localhost”字符串是否存在于以下位置来解决它:

var environ = window.location.host;

Then you can simply do:

然后你可以简单地做:

if (environ === "localhost") {
    var baseurl = window.location.protocol + "//" + window.location.host + "/" + "shared/";
} else {
    var baseurl = window.location.protocol + "//" + window.location.host + "/";
}

Then you can add baseurlin front of whatever url you need to reference.

然后你可以baseurl在你需要引用的任何 url 前面添加。

回答by iivel

The url

网址

var url = "/Shared/AskReason.ashx?REASON=" + reason; 

Is looking for the file in the root directory [since it is an absolute path], effectively

正在寻找根目录中的文件[因为它是绝对路径],有效

http://localhost/Shared/AskReason.ashx

You should include the name of the virtual directory OR determine the appropriate structure:

您应该包括虚拟目录的名称或确定适当的结构:

Starting without the / will give you a relative path ... if you need to navigate directories use ../Shared/ style of notation, or finally use your servers Directory command to determine your current path.

不带 / 开头会给你一个相对路径......如果你需要导航目录使用 ../Shared/ 符号样式,或者最后使用你的服务器目录命令来确定你的当前路径。

回答by Willy David Jr

I have the same issue with ASP.NET MVC with my AJAX call on a separate .js file. This is how it looks:

我对 ASP.NET MVC 有同样的问题,我在单独的 .js 文件上调用了 AJAX。这是它的外观:

 return $.ajax({
            type: "POST",
            url: '/Dashboard/Execute',
            contentType: "application/json; charset=utf-8",
            data: filter,
            dataType: "json",
        });

This works fine on my local, of course. But when deployed on a subdirectory in IIS, e.g.

当然,这在我的本地工作正常。但是当部署在 IIS 的子目录中时,例如

wwwroot/appsite/subdomainfolder/

This will trigger 404 Not Foundas it didn't attach the subdomainfolder on the URL.

这将触发404 Not Found因为它没有在 URL 上附加子域文件夹。

If I remove the

如果我删除

"/"

“/”

at the beginning of the URL, it will generate it like this one:

在 URL 的开头,它会像这样生成它:

http://localhost/subdomainfolder/Dashboard/Dashboard/ExecuteReader

Which again will trigger the 404 Not Found issue.

这将再次触发 404 Not Found 问题。

So here are the two options for my workaround:

所以这是我的解决方法的两个选项:

Remove the backslash and remove the name of the controller (Dashboard on this case):

删除反斜杠并删除控制器的名称(在这种情况下为仪表板):

return $.ajax({
            type: "POST",
            url: '/Execute',
            contentType: "application/json; charset=utf-8",
            data: filter,
            dataType: "json",
        });

Or, stay as it is, just add double period at the beginning of the URL:

或者,保持原样,只需在 URL 的开头添加双句号:

return $.ajax({
            type: "POST",
            url: '../Dashboard/Execute',
            contentType: "application/json; charset=utf-8",
            data: filter,
            dataType: "json",
        });