我正在使用 jQuery 调用 Controller , Controller 正在返回一个值。 jQuery 正在获取该值,但它没有将其设置为我的变量并返回它。我在这里做错了什么?
GetDepartmentID 被调用,值为 1。它转到 Controller , Controller 返回部门 ID,即 1。
console.log("Inside-DepartmentID "+ data) 在控制台中显示 1,所以我知道数据正在从 Controller 返回。
然后我将数据分配给departmentID。把它返还。然后我的外部函数尝试 console.log 返回,但它是未定义的。我不明白。
.change 函数调用 GetdepartmentID(1);
function GetDepartmentID(functionID) {
var departmentID;
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, function (data) {
console.log("Inside-DepartmentID " + data)
departmentID = data;
});
return departmentID;
}
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
var value = GetDepartmentID(functionID.val());
console.log("test " + value);
//GetOwnerList(value);
});
最佳答案
您可以尝试这种方式来处理AJAX调用返回的数据。
function processResults(departmentID)
{
console.log("test " + departmentID);
GetOwnerList(departmentID);
// Someother code.
}
function GetDepartmentID(functionID, callBack) {
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, function (data) {
console.log("Inside-DepartmentID " + data)
callBack(data); //Invoke the callBackhandler with the data
});
}
jQuery(function(){
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
GetDepartmentID(functionID.val(), processResults); // pass function as reference to be called back on ajax success.
});
});
或者只是这样做:这与将所有后续处理代码放入 getJSON 处理程序中一样好。
function processResults(data)
{
//handle the data here.
}
function GetDepartmentID(functionID) {
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, processResults);
}
jQuery(function(){
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
GetDepartmentID(functionID.val()); // pass function as reference to be called back on ajax success.
});
});
关于javascript - jQuery 获取 json 数据但不返回/赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864449/