How can I return a variable from a $.getJSON function

前端 未结 6 1351
迷失自我
迷失自我 2020-11-27 03:01

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
         


        
6条回答
  •  时光说笑
    2020-11-27 03:35

    Yeah, my previous answer does not work because I didn't pay any attention to your code. :)

    The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:

    var studentId = null;
    j.getJSON(url, data, function(result)
    {
        studentId = result.Something;
    });
    
    // studentId is still null right here, because this line 
    // executes before the line that sets its value to result.Something
    

    Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.

提交回复
热议问题