开发者

How to set global variables in jQuery/JavaScript?

I have an ajax function:

    $.ajax({
        url: 'http://localhost/process.php',
        type: 'post',
        data: '',
        success: function(output) {

va开发者_如何学Cr animal = output

        }
    });

I would like the var animal to be set globally so I can call it anywhere on the page even outside the ajax function's success callback. How to do this?


Declare it outside of any function or jQuery construct

var animal = null;

$(function(){
    $.ajax({
        url: 'http://localhost/process.php',
        type: 'post',
        data: '',
        success: function(output) {
            animal = output
        }
    });
});


If you want it to be a global variable, then declare it as a global variable. Generally you do this by putting

var animal;

around the top of your .js file. Then any reference to animal inside your code will be the global variable, unless you re-use the name somewhere else in the scope.


IF you want to do it dynamically.

jQuery.globalEval()

http://api.jquery.com/jQuery.globalEval/

This method behaves differently from using a normal JavaScript eval() in that it's executed within the global context (which is important for loading external scripts dynamically).

$.globalEval( 'var animal = ' + output );


Remove the var to make the variable global.

Note however that working with globals is generally viewed as bad practice, because they are very hard to debug.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜