我有这个AJAX帖子功能:
var library = {
ajaxPost: function (endpoint, data, callback, returnSelector, dataType, type) {
$.ajax({
type: (type ? type : "POST"),
url: endpoint,
data: data,
dataType: (dataType === undefined ? "JSON" : dataType),
success: function (result) {
if (callback != null && callback !== undefined) {
callback(returnSelector === false ? result : $(result));
}
console.log("endpoint = " + endpoint);
console.log("data = " + data);
console.log("callback = " + callback);
console.log("returnSelector = " + returnSelector);
console.log("dataType = " + dataType);
console.log("type = " + type);
console.log("result = " + result);
},
error: function (xhr, ajaxOptions, thrownError) {
// show an error message
console.error(xhr.status);
console.error(thrownError);
},
complete: function () {
}
});
}
};
这就是调用函数的地方:
var modalCallbacks = {
companyCreate: function (result, modalDom) {
callModalBasicInit();
var saveButton = modalDom.find(".modal-footer button[type='submit']");
saveButton.unbind("click");
saveButton.on("click", function (e) {
e.preventDefault();
var data = modalDom.find("form").serializeObject();
data["returnJson"] = true;
library.ajaxPost("/companies/edit/", data, function (result) {
if (result.success) {
modalDom.modal('hide');
var dropdown = $("#create-modal #CompanyID");
var currentSelected = dropdown.find("option:selected");
if (currentSelected.length) {
currentSelected.removeAttr("selected");
}
var newOption = '<option value="' + result.company.CompanyID + '">' + result.company.Name + '</option>';
dropdown.append(newOption);
dropdown.val(result.company.CompanyID);
}
}, false);
});
}
}
我的问题是你在if语句中看到的jQuery:if(result.success) { }
永远不会被执行。我有console.logged result.success它出现了undefined,我意识到这是问题的主要部分,但我怎么能让它返回true?其他所有功能都按预期运行,数据将保存到数据库中。
我在控制台中记录了一些内容:
endpoint = /companies/edit/
data = [object Object]
callback = function (result) {
if (result.success) {
modalDom.modal('hide');
var dropdown = $("#create-modal #CompanyID");
var currentSelected = dropdown.find("option:selected");
if (currentSelected.length) {
currentSelected.removeAttr("selected");
}
var newOption = '<option value="' + result.company.CompanyID + '">' + result.company.Name + '</option>';
dropdown.append(newOption);
dropdown.val(result.company.CompanyID);
}
}
returnSelector = false
dataType = undefined
type = undefined
result = [object Object]