所以,我做一個正常的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
。
該解決方案需要在本地和服務器上都能工作。因此,在本地測試時,document.domain會返回localhost。按照上面的方式進行操作時,它會嘗試打開url http:// localhost:#####/localhostcontroller/action'。 – ScubaSteve