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

发布于 2024-10-19 00:19:58 字数 1303 浏览 3 评论 0原文

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

这行:

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

是什么导致了问题。

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

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

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

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

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

谢谢, 麦克风

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

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.

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

许一世地老天荒 2024-10-26 00:19:58

Pointy 的方式 有效,但你必须知道提前确定要部署的位置。

或者,不要以 / 开头相对路径:

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

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

http://localhost/myapp/index.aspx

...那么这将解析为

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

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

Alternately, simply don't start the relative path with 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
小…红帽 2024-10-26 00:19:58

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

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

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

然后“ root”变量根据“/myapp”或其他内容的配置进行扩展。

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

风为裳 2024-10-26 00:19:58

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

var environ = window.location.host;

然后您可以简单地执行以下操作:

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

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

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:

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 baseurl in front of whatever url you need to reference.

月棠 2024-10-26 00:19:58

url

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

正在根目录中查找文件[因为它是绝对路径],实际上

http://localhost/Shared/AskReason.ashx

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

不带 / 开始将为您提供相对路径...如果您需要使用 ../Shared/ 符号风格来导航目录,或者最后使用服务器 Directory 命令来确定当前路径。

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.

高冷爸爸 2024-10-26 00:19:58

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

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

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

wwwroot/appsite/subdomainfolder/

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

如果我删除

“/”

如果 URL 开头有

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

,则会生成如下所示的 URL:这又会触发 404 Not Found 问题。

因此,我的解决方法有两个选项:

删除反斜杠并删除控制器的名称(本例中为仪表板):

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

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

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

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

 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.

wwwroot/appsite/subdomainfolder/

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

If I remove the

"/"

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

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

Which again will trigger the 404 Not Found issue.

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:

return $.ajax({
            type: "POST",
            url: '../Dashboard/Execute',
            contentType: "application/json; charset=utf-8",
            data: filter,
            dataType: "json",
        });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文