2016-03-16 76 views
1

所以,我做一個正常的Ajax調用是這樣的:爲什麼url變量會導致ajax相對url的問題?

$.ajax({ 
    type: "GET", 
    url: this.Controller + "/" + this.Action, 
    data: data, 
    cache: false, 
    dataType: "json", 
    success: function (data) { 
     var json = $.parseJSON(data); 
     $("#Debug").html(JSON.stringify(json, undefined, 4)); 
    }, 
    error: function (jqXHR, textStatus, errorThrown) { 
     var errorMessage = "Unable to retrieve data." 
     if (jqXHR.responseText != null) { 
      errorMessage += "\n\nError Message: " + jqXHR.responseText; 
     } 
     alert(errorMessage); 
    } 
}); 

當我使用相對路徑爲AJAX URL,它工作得很好,只要有在當前頁面的URL不URL變量。它會正確地去http://domain.com/controller/action

如果有一個url變量,ajax url試圖擊中http://domain.com/controller/controller/action,它不存在。

如果我添加斜線像這樣:

url: "/" + this.Controller + "/" + this.Action 

這修正了該URL變量引起的問題,但只能在本地。當我部署到我們的服務器時,我的應用程序位於一個子目錄中,因此url是http://domain.com/myapp。斜線解決方案不起作用,因爲根目錄是http://domain.com而不是http://domain.com/myapp

回答

0

你可以試試這個$.ajax({url: document.domain + this.Controller ... })

+0

該解決方案需要在本地和服務器上都能工作。因此,在本地測試時,document.domain會返回localhost。按照上面的方式進行操作時,它會嘗試打開url http:// localhost:#####/localhostcontroller/action'。 – ScubaSteve

0

我嘗試了各種方式來通過JS來做到這一點,他們都沒有爲服務器(子目錄)和本地(無)工作。

因此,我的解決方案是在我的web.config的appsettings中添加子目錄的名稱。在主web.config中,我有:<add key="Subdirectory" value="" />

在web.release.config,我有:<add key="Subdirectory" value="SubDirectoryName" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />

把它置放在web.config中的空白,並在web.release.config設置它,只有在發佈到服務器時,子目錄纔會被轉換和設置。

在_Layout.cshtml頁,我有:

<script> var subdirectory = '@ConfigurationManager.AppSettings["Subdirectory"]'; if (subdirectory != '') { subdirectory = '/' + subdirectory; } </script>

然後,隨時隨地在我的JS,我試圖做一個Ajax調用,我的URL設置爲:

url: subdirectory + "/" + this.Controller + "/" + this.Action, // subdirectory comes from _Layout.cshtml

相關問題