我的 MVC 应用程序中有一个像下面这样的 ajax 函数
$.ajax({
type: "GET",
url: '/UpdateDetail/GetlocationAjax',
data: { cityId: cityId },
dataType: "json",
success: function (result) {
$.each(result, function (key, val) {
workloc.append(
$('<option></option>').val(val).html(key)
);
});
},
error: function (result) {
}
});
当我从 Visual Studio 运行应用程序时,此功能完美运行,但当我将其部署到 IIS 7.5 时,此 ajax 功能无法正常工作
我尝试将 URL 设为 url: '../UpdateDetail/GetlocationAjax',
然后,同样的方法在本地级别也不起作用,但我有另一个应用程序,在其中将 ajax 函数调用为
$.ajax({
type: "GET",
url: '../Preapproval/Getactivitycodetype',
dataType: "json",
success: function (result) {
$("#code_type-" + index)
.append($('<option></option>').val("").html("--Type--")
);
$.each(result, function (key, val) {
$("#code_type-" + index).append(
$('<option></option>').val(val).html(key)
);
});
},
error: function (result) {
}
});
这在本地和 IIS 中都可以完美运行。
我的第一个 ajax 函数在 IIS 中无法工作可能是什么问题?
最佳答案
$.ajax({
type: "GET",
url: '@Url.Action("GetlocationAjax", "UpdateDetail")',
data: { cityId: cityId },
dataType: "json",
success: function (result) {
$.each(result, function (key, val) {
workloc.append(
$('<option></option>').val(val).html(key)
);
});
},
error: function (result) {
console.log(result);
}
});
为此,您必须将 js 保留在 cshtml 页面中,而不是外部 js 文件中,因为它使用 MVC 函数 Url.Action()
;
如果你想将js保留在外部文件中,那么创建一个隐藏字段并从隐藏字段中读取url,如下所示
<input type="hidden" id="ajaxUrl" value='@Url.Action("GetlocationAjax", "UpdateDetail")' />
然后在你的ajax调用脚本中使用:
var url = $("#ajaxUrl").val();
$.ajax({
type: "GET",
url: url,
还可以使用 chrom 检查器来跟踪网络请求 F12,网络选项卡。
关于jquery - Ajax 功能在本地运行时工作,但部署在 IIS 中时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32622585/