2012-10-29 20 views
1

这可能很简单,但我已经停留了一段时间。使用ajax调用wcf方法时的绝对URL

我有一个用户控制它调用这样的方法:在我的网站

$(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的?

Attemps:在前面

把斜线,像

url: "/Services/ForumOperationService.svc/GetTags" 

这是行不通的。我收到了404错误:http://localhost:16481/Services/ForumOperationService.svc/GetTags" (gives 404)

相反,它应该是

http://localhost:16481/Client/Services/ForumOperationService.svc/GetTags" 
+0

您是否尝试过只用URL: “/Services/ForumOperationService.svc/GetTags”, – Tariqulazam

+0

是的,我试过:-)给我一个404电话(我会更新后) –

回答

2

如果您的应用程序始终位于同一位置,请使用绝对路径("/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"); 

http://jsfiddle.net/HackedByChinese/tRMSj/

1

要相对于网站的客户端根目录的路径,在前面加上斜杠:

url: "/Client/Services/ForumOperationService.svc/GetTags" 

注意 - 如果Client是虚拟目录/应用程序在IIS Express中,当它安装时它不会有Client位,您需要更改它。

+0

不工作 - 更新后:-) –

+1

我已经更新了它 - 同时提醒一下:) – Fenton