jQuery获取jSon数据但没有返回/赋值

时间:2013-05-31 19:23:48

标签: javascript jquery ajax asp.net-mvc

我使用jQuery来调用控制器,控制器返回一个值。 jQuery正在获取值但是它没有将它设置为我的变量并返回它。我在这做错了什么?

调用GetDepartmentID,值为1.它转到控制器,控制器返回的departmentID为1.

控制台中的

console.log(“Inside-DepartmentID”+数据)显示为1,因此我知道数据正在从控制器返回。

然后我将数据分配给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);
    });

1 个答案:

答案 0 :(得分:2)

您可以尝试这种方式来处理从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.
        });
     });
相关问题