我一生都无法弄清楚为什么这个 ajax 调用不断返回错误。(我是网络世界的新手,所以我猜我在这里遗漏了一些简单的东西:S)
在我的 cshtml 中,我有一个包含标签的 Select2 多值选择框。然后,当我尝试通过对控制器进行 ajax 调用来删除标签时,即使我的操作成功完成,它也会返回错误:
$(function () {
$('#tagSelector').select2({
placeholder: 'Select a tag...',
multiple: true,
ajax: {
url: '@Url.Action("SearchTags", "UnitDetails")',
dataType: 'json',
data: function (term, page) {
return {
searchTerm: term
};
},
results: function (data, page) {
return { results: data };
}
},
createSearchChoice: function (term) {
return {id: term, text: term};
}
}).on("removed", function(e) {
var url = '@Url.Content("~/UnitDetails/UnTagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.choice.text;
console.log(id + " : " + tagName);
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function() {
toastr.options = {
"closeButton": true,
"debug": false,
"positionClass": "toast-top-right",
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr.success("Tag deleted from unit.", "Success!");
},
error: function() {
toastr.options = {
"closeButton": true,
"debug": false,
"positionClass": "toast-top-right",
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr.error("Could not delete tag from unit.", "Oops!");
}
});
});
在我的控制器中,UnTagUnit(int id, string selectedItem)
看起来像这样:
[HttpGet]
public JsonResult UnTagUnit(int id, string selectedItem)
{
try
{
UnitClient.UnTagUnit(id, selectedItem);
// what to return if success?
}
catch (Exception e)
{
// Log and handle
// what to return if error?
}
}
如前所述,该方法运行良好,我的意思是UnTagUnit(id, selectedItem)
成功完成该部分(wcf 服务)。
所以,我想我要么错过了什么,要么做了一些根本错误的事情。还尝试了不同的方法,如返回new Json(new { success = true} )
。