开发者

How to control the code execute order when using ajax to get and assign data in jquery?

these are part of my code :

my problem is the userName assign expression was execute before the function getUserInfomation(userId) , even thought I put the getUserInfomation() in front of them.

global variable:

userInformation = {};

function with event called to assign values:

function assignValues(){
   getUserInfomation(userId);

       userName =  userInformation['user_name'];  // undefined
       userNickName= userInformation['user_nickname'];// undefined

}

function to get data from database via AJAX:

function getUserInfomatio开发者_StackOverflown (userId){


            $.ajax({
              url: 'include/user.login.process.php',
              data:({userId: userId }),
              success: function(data) {

                if(data){
                    JSON.parse(data, function (key, value) {
                        userInformation[key] = value;
                        console.log(key +' value is '+obj.userInformation[key]);
                    });
                }
             }
           });

        }

thank you very much!!


$.ajax method is asynchronous. It you have to change to place all code which have to be executed after ajax request into callback function: So, you have to use a code like this:

function getUserInfomation (userId){
        $.ajax({
          url: 'include/user.login.process.php',
          data:({userId: userId }),
          success: function(data) {

            if(data){
                JSON.parse(data, function (key, value) {
                    userInformation[key] = value;
                    console.log(key +' value is '+obj.userInformation[key]);

                    assignValues();
                });
            }
         }
       });

    }

Also, you can just call ajax function synchronously. But is a bad practice because you will lose ajax advantages.

        $.ajax({
          url: 'include/user.login.process.php',
          data:({userId: userId }),
          async:false,
          success: function(data) {
          ...


You need to do your assignment operations inside the success function of the .ajax call

The $.ajax is an asynchronous operation so when you call it, it returns immediately executing the next line of your code (in this case userName = ....), but you haven't got the data back from the server yet, that's what the success callback is for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜