我正在使用 MVC5 并调用 $.ajax 以根据客户选择(某些分割属于某些客户)填充我的“分割”下拉列表。当我转到我的添加 View 时,以下 JavaScript 工作正常。但是,当我转到“编辑” View 并运行完全相同的脚本时,它不起作用。
我在 getSubdivisions() Controller 方法中放置了一个断点,它在添加页面上运行良好。但是,当我在“编辑”页面上时,$.ajax 调用永远不会触发 Controller 操作。 $.ajax 调用失败。有什么问题?
我在添加和编辑 View 的末尾都有以下行:
@Scripts.Render("~/bundles/schedule")
~/bundles/schedule 文件在 BundleConfig.cs 中定义:
bundles.Add(new ScriptBundle("~/bundles/schedule").Include("~/Scripts/mainsys/schedule.js"));
这是我的 JavaScript...
try {
$('#CustomerID').change(function () {
getSubdivisions();
});
getSubdivisions();
}
catch (ex) {
alert(ex.message);
}
function getSubdivisions() {
custId = $('#CustomerID').val();
// remove all of the current options from the list
$('#SubdivisionID').empty();
// send request for list of subdivisions
var jqxhr = $.ajax({
url: './getSubdivisions',
type: 'POST',
data: '{ customerId: ' + custId.toString() + ' }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
async: true
});
// received list of models...
jqxhr.done(function (data) {
if (data == null) return;
try {
var ddl = $('#SubdivisionID');
// add each item to DDL
$.each(data, function (index, value) {
ddl.append($('<option></option>', { value: data[index].SubdivisionID }).html(data[index].SubdivisionName))
});
}
catch (ex) {
alert("Done, but with errors!\n" + ex.message);
}
});
// failed to retrieve data
jqxhr.error(function (result, errorText, thrownError) {
alert("Error! Failed to retrieve models! " + errorText + "\n" + thrownError);
});
}
这是我的 Controller 方法...
[HttpPost]
public string getSubdivisions(int customerId)
{
try
{
if (customerId <= 0) return null;
List<s84_Subdivision_Short> lst = s84_Subdivision.listItemsShort(customerId);
string s = JsonConvert.SerializeObject(lst);
return s;
}
catch (Exception)
{
return "";
}
}
jqxhr.error...
errorText is "parsererror" and thrownError is "Invalid character."
更新:在 Firefox 中,错误显示为“JSON.parse:意外字符”
请您参考如下方法:
我更改了 $.ajax 调用,使其不使用相对路径...现在一切正常。
