问题描述
好的,我有一个具有以下功能的JavaScript文件:
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);
}
此行:
var url = "/Shared/AskReason.ashx?REASON=" + reason;
是引起问题的原因.
在VS 2010中调试应用程序-此调用适用于我的ashx处理程序.
In VS 2010 debugging the app - this call works to my ashx handler.
当我将项目移动到虚拟目录时-示例 http://localhost/myapp
When I move the project to a virtual directory - example http://localhost/myapp
此代码将中断,我必须将javascript更改为此:
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?
谢谢,迈克
推荐答案
是可行的,但是您必须事先知道要在哪里部署它.
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
...然后将解决
http://localhost/myapp/Shared/AskReason.ashx?REASON=foo
这篇关于Javascript Ajax调用中的相对路径问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!