jquery getJSON function timing issue

僤鯓⒐⒋嵵緔 提交于 2019-12-30 09:09:06

问题


I think my program is skipping result of JSON call. Is it possible to make a closure function here or make the program wait for JSON call to return?

function username_not_duplicate(username) {
   var function_name = "get_username";
   var parameters = [username];
   var url = "/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   $.getJSON(url, function(user_name) {
      if (user_name == true) {     
         return true;
      }
   });
   return false;
}

回答1:


The $.getJSON() API call is asynchronous. You can make it synchronous by using $.ajax() this way:

function username_not_duplicate(username) {
   var function_name = "get_username";
   var parameters = [username];
   var url = "/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   var rslt = false;
   $.ajax({
     async: false,
     url: url,
     dataType: "json",
     success: function(data) {
       if (data == true) {     
         rslt = true;
       }
     }
   });
   return rslt;
}



回答2:


Drew's answer is nearly perfect, just missing one bracket and comma for IE.

function username_not_duplicate(username) {
   var function_name = "get_username"; 
   var parameters = [username]; 
   var url = "camps/includes/get_functions.php?function_name=" + function_name + "&parameters=" + parameters;
   var rslt = false; 
   $.ajax({ 
         async: false, 
         url: url, 
         dataType: "json", 
         success: function(data) {
           if (data == true) {                   
             rslt = true; 
           }
        }, 
    });
    return rslt; 
}



回答3:


Another choice is to use a call back function and pass it to the function that executes the getJSON as:

//this is the function that executes my getJSON
//callback is the name of my callback function
function getMyData( callback ){

  //here you do your getJSON call
  $.getJSON(url, function(items){

    //do your stuff here

    //call your function here (at the end)
    callback();

  });

}

This way your callback function will be called at the end of the getJSON call.




回答4:


Yeap, username_not_duplicate just returns false immediately because getJSON is asynchronous (ie non-blocking). The return true statement just returns true from the response handler. Normally, you shouldn't do such a blocking calls you're trying to achieve. I suppose you can consider remembering of a state of the request somewhere globally.



来源:https://stackoverflow.com/questions/3419026/jquery-getjson-function-timing-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!