简体   繁体   中英

How to Assign value to global variable and use it in other functions in jquery/javascript?

Declare global variables(jquery):

 $.mynamespace = {  myVar : "something" }; 

I will do some operations with xml, after that will assign some other value to myVar and call to function test() will again change the value of myVar. Then I want the value of var must be same as I changed in test() function.

    $(document).ready(function(){
        //Some XML oprations
        $.get("students.xml",{},function(xml){
            $.mynamespace.myVar="ewewewewewew";
            test();
        });
        //value of $.mynamespace.myVar must be test
        alert($.mynamespace.myVar);
     });

     function test(){
        alert($.mynamespace.myVar );
         $.mynamespace.myVar="test";
     }

Ajax stands as Asynchronous JavaScript and XML which means that the calls are Asynchronous. When AJAX is done the sucessful function is called. It can be called anytime. So when javascript reaches the code it just goes through and when ajax is ready success function is called.

There are 2 solutions.

  1. You do something with variable when ajax request is done in sucessful function
  2. You do something with variable after the ajax code but you need to use param async: false which makes Ajax NO ajax :) but some kind of SJAX .

You can use closures instead of global vars to do the same thing

(function($){
  var myNs = {};

  $(document).ready(function(){ 

    //Some XML oprations
    $.get("students.xml",{async: false},function(xml){
        myNs.myVar="ewewewewewew";
        test();
    });
        //value of $.mynamespace.myVar must be test
        alert(myNs.myVar);
  });

     function test(){
        alert(myNs.myVar );
         myNs.myVar="test";
     }
})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM