Jquery 使用ajax调用wcf方法时的绝对URL
这可能很简单,但我已经被困了一段时间 我有一个用户控件,它调用如下方法:Jquery 使用ajax调用wcf方法时的绝对URL,jquery,asp.net,ajax,json,absolute-path,Jquery,Asp.net,Ajax,Json,Absolute Path,这可能很简单,但我已经被困了一段时间 我有一个用户控件,它调用如下方法: $(document).ready(function () { $("#myabtags").tagit({ tagSource: function (request, response) { $.ajax({ type: "POST", url: "Services/F
$(document).ready(function () {
$("#myabtags").tagit({
tagSource: function (request, response) {
$.ajax({
type: "POST",
url: "Services/ForumOperationService.svc/GetTags",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: '{"prefix":"' + request.term + '"}',
success: function (data) {
response(data.GetTagsResult);
}
});
}
});
});
然而,这个用户控件在我的网站上有好几个地方使用。例如,在根目录下,/Admin/和其他几个目录下
我想做一些类似的事情:
url: "~/Services/ForumOperationService.svc/GetTags"
在jQuery中如何做到这一点
尝试:
把斜线放在前面,就像
url: "/Services/ForumOperationService.svc/GetTags"
那不行。我得到一个404错误:http://localhost:16481/Services/ForumOperationService.svc/GetTags“(给出404)
应该是这样
http://localhost:16481/Client/Services/ForumOperationService.svc/GetTags"
要使路径相对于网站客户端的根,请在前面加一个斜杠:
url: "/Client/Services/ForumOperationService.svc/GetTags"
注意-如果
Client
是IIS express中的虚拟目录/应用程序,并且安装时没有Client
位,则需要对其进行更改。如果应用程序始终位于同一位置,请使用绝对路径(“/Services/ForumOperationService.svc/GetTags”
)。但是,如果您将同一代码库部署到多个站点,这些站点可能具有不同的根路径,我将使用以下技巧:
它的工作原理是这样的:我假设我的应用程序的所有JS脚本都在一个文件夹中,比如scripts
。然后我有一个公共JS文件,其中包含实用程序,包括保存绝对根URL的位置和生成绝对URL的方法。然后我用该src搜索脚本块,并提取根URL
(function($)
{
$.myapp = {};
var $a = $.myapp;
$.extend($a, {
rootUrl: '',
makeAbsoluteRootPath: function(path) {
return path.replace('~/', $a.rootPath);
}
});
var tag = $('script[src*="scripts"]').first();
if (tag.length > 0) {
var url = tag.attr('src').replace(/\/?(scripts).+$/i, '/');
$a.rootPath = url;
}
})(jQuery);
现在,您可以动态解析绝对根路径:
url: $.myapp.makeAbsoluteRootPath("~/Services/ForumOperationService.svc/GetTags");
您是否仅使用url尝试过:“/Services/ForumOperationService.svc/GetTags”,是的,我尝试过:-)给我打了404电话(我将更新帖子)