问题描述
说我有网站
其中,虚拟就是虚拟目录
Say I have the site http://localhost/virtualwhere virtual is the virtual directory
我有一个JavaScript文件中使用JQuery定义一个Ajax请求
I have an Ajax request that is defined in a javascript file using JQuery
$.getJSON("/Controller/Action")
在这个被调用时,客户端试图找到在根级别的URL,即
When this is called, the client tries to find the url at the root level i.e. http://localhost/Controller/Action
如果我在添加波浪号(〜)符号,它变成
http://localhost/virtual/~/Controller/Action
If I add the tilde (~) symbol in, it turns into http://localhost/virtual/~/Controller/Action
应该(如果它是做什么我想)解析
It should (if it was to do what I wanted) resolve to http://localhost/virtual/Controller/Action
这是如何解决这一问题的任何想法?
Any ideas on how to fix this?
推荐答案
我成功地使用这个解决方案
I used this solution successfully
将下面的元素在你的母版
Place the following element in your masterpage
<%= Html.Hidden("HiddenCurrentUrl", Url.Action("Dummy"))%>
在主JavaScript文件
声明一个全局变量
Declare a global variable in your main javascript file
var baseUrl = "";
设置的baseUrl为HiddenCurrentUrl当你的JavaScript加载
Set baseUrl to the value of "HiddenCurrentUrl" when your javascript is loaded
baseUrl = $("#HiddenCurrentUrl").val();
baseUrl = baseUrl.substring(0, baseUrl.indexOf("Dummy"));
使用的baseUrl
Use baseUrl
$.getJSON(baseUrl + "Action")
编辑改进方案
在控制器
ViewBag.BaseUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath + "/";
在你的母版页
<script type="text/javascript">
var YourNameSpace = YourNameSpace || {};
YourNameSpace.config = {
baseUrl: "@ViewBag.BaseUrl"
}
</script>
使用您的baseUrl
Use your baseUrl
$.getJSON(YourNameSpace.config.baseUrl + "Action")
这篇关于在JavaScript的虚拟目录不知道虚拟目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!