2010-03-29 45 views
3

我想要運行的Web服務中的功能(.asmx文件)JS文件中動態獲取基礎URL

$.ajax({ 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     url: '/Admin/WebSrvcs/Management.asmx/f_SearchLabel', 
     data: "{_sQuery:'" + obj.value + "'}", 
     dataType: "json", 

但我不知道在哪裏會是我的根URL(http://localhost:4399/VirDir或別的東西,它可能是)地址在js文件中。我需要到達應用程序的根文件夾才能找到asmx文件。

$.ajax({ 
     type: "POST", 
     contentType: "application/json; charset=utf-8", 
     url: 'http://localhost:4399/virDir/Admin/WebSrvcs/Management.asmx/f_SearchLabel', 
     data: "{_sQuery:'" + obj.value + "'}", 
     dataType: "json", 

我正在使用Visual Studio 2008和C#構建網站。

任何幫助將不勝感激

+0

從根開始,就像你在第一個例子中做的那樣,就足以訪問web服務了嗎?爲什麼你會使用絕對URL而不是相對URL? – Joop 2010-03-30 06:08:58

+0

在我的電腦中,我正在處理http:// localhost:4399/virDir url。但是當我將Web應用程序發佈到服務器時,我無法訪問js文件。 – uzay95 2010-03-30 12:05:34

回答

0

也許我失去了一些東西,但如果JavaScript和網頁都在同一臺服務器上,你可以只用JS做這樣的事情:

<script> 
var pd = parent.document; 

var location = pd.location.protocol + "//" + pd.location.host; 

alert(location); 
</script> 

此外,你可以寫一個HTTP處理程序,您的JavaScript,當請求進來後,您可以通過獲取請求的完整url來填寫變量。

internal static string GetFullPath(HttpRequest request) 
    { 
     Uri uri = request.Url; 
     string fullUrl = String.Format("{0}{1}{2}{3}", (request.IsSecureConnection) ? "https://" : "http://", 
             uri.Host, (uri.IsDefaultPort) ? "" : String.Format(":{0}", uri.Port), uri.AbsolutePath); 
     Int32 index = fullUrl.LastIndexOf("/"); 
     fullUrl = fullUrl.Remove(index + 1, (fullUrl.Length - 1) - index); 

     return fullUrl; 
    } 
0

有一些方法可以做到這一點。

之一將是遍歷頁面上的<script>元素,並檢查src屬性包含所需的腳本名稱(例如<script src="my/js/dir/myScript.js"></script>),然後提取所需的路徑。

雖然這可能是一種簡單的方法將端口連接到其他服務器,但可能會出現「myScript.js」不止一次位於不同位置的問題,所以它不會那麼可靠。

另一種方式做,這將包括某種形式的配置文件,在那裏你可以設置你的應用程序設置,使用這樣的事情:

文件:APP-config.js


var AppConfig = { 
    "someImportantPath" : "some/important/path", 
    "anotherPath" : "another/path" 
} 

你可以在你的應用程序中使用這個全局變量。

+0

你是對的,但我在我的機器上使用這個基地址:http:// localhost:4399/myVirDir/...但是當我發佈這個站點到服務器時,它的基地址改變了http:// www .hostname.com/theirVirDir – uzay95 2010-03-29 17:45:00

1

如果您使用母版頁那麼這就會變得很方便:

在母版頁的HEAD:

<script type="text/javascript"> 
    var baseUrl = '<%# ResolveUrl("~/") %>'; 

    function ResolveUrl(url) { 

     if (url.indexOf("~/") == 0) { 
      url = baseUrl + url.substring(2); 
     } 

     return url; 
    } 

</script> 

在母版頁的.cs頁:

protected void Page_Load(object sender, EventArgs e) 
    { 
     Page.Header.DataBind(); 
    } 

然後在您的javascript中:

ResolveUrl("~/Admin/WebSrvcs/Management.asmx/f_SearchLabel")