开发者

Store return data from $.post call for later use?

// inside $(document).ready function...

var name = '';

function test()
{
    $.post('/student/get-info', function(data) {
        var student = $.parseJSON(data);            
        name = student.name;
    });

    // use 'name' to do something here or outside of this function
}

// I want to use 'name' later without calling '/student/get-info' again

Ed开发者_运维技巧it: name = ''

Edit: The question is the thread title. My code doesn't work. After the post call, name is still empty. That's the problem.

Edit: $.getJSON is wrong there, $.parseJSON instead


declare var student within the global scope for it to be accessible elsewhere, rather than inside the document.ready function

Or you can not clutter the global vars until you need function test(){} and you could just remove the var prefix, which would make it global (ie delete var name = 0;)

Edit :: Plus it should be noted that AJAX is asynchronous, so what you're doing won't work. Add to the call back to do what you want rather than after it (as the student will be 0 still), or stop the call being asyncrhonous


If you want a variable to be global even outside of the $(document).ready then you can initialize it outside of that - maybe just before the $(document).ready function.

I think the problem you might be having is that you are checking the name variable later in the code, but before name is populated. All the code that depends on name should be run after the ajax call retrieves data. So either in the $.post() callback function or after a timeout or event that checks if the variable name has been populated yet.


If it's all in the $(document).ready function, you'll have access to it as it's local to that scope.

Way to provide some context, and actually test your code before asking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜