2012-07-28 151 views
1

我遇到的問題是我無法訪問函數外的變量值。我剛剛開始學習jQuery,我非常喜歡它,但是這讓我陷入了一段時間。無法訪問jQuery中的變量值

我已閱讀過與此相關的其他線索,但這些方法仍然無效!

$.get("/new/verify.php", { username: username, email: email }, 
     function(data){ 
      var stop_loading = '0'; 
      if(data == 'username') 
      { 
       alert('username taken'); 
       $('#username_taken_error').show(); 
       $('#username').focus(); 
       stop_loading = '1'; 
      }else if(data == 'email') { 
       alert('email taken'); 
       $('#email_taken_error').show(); 
       $('#email').focus(); 
       stop_loading = '1'; 
      }else if(data == 'username|email') { 
       alert('username/email taken'); 
       $('#username_taken_error').show(); 
       $('#email_taken_error').show(); 
       $('#username').focus(); 
       stop_loading = '1';  
      } 
    }); 

    alert(stop_loading); 

    if(stop_loading == '1') { 
     alert('Stop loading'); 
     return false; 
    } 

回答

2

作爲$.get()執行AJAX請求是異步的,所以內的$.get()成功函數調用另一個函數與stop_loading像以下:

$.get("/new/verify.php", { username: username, email: email }, 
     function(data){ 
      var stop_loading = '0'; 
      if(data == 'username') 
      { 
       alert('username taken'); 
       $('#username_taken_error').show(); 
       $('#username').focus(); 
       stop_loading = '1'; 
      }else if(data == 'email') { 
       alert('email taken'); 
       $('#email_taken_error').show(); 
       $('#email').focus(); 
       stop_loading = '1'; 
      }else if(data == 'username|email') { 
       alert('username/email taken'); 
       $('#username_taken_error').show(); 
       $('#email_taken_error').show(); 
       $('#username').focus(); 
       stop_loading = '1';  
      } 
      // call function with stop_loading 
      callAFunction(stop_loading); 
    }); 

    // this function will be called 
    // with stop_loading arugment 

    function callAFunction(stop_loading){ 
     if(stop_loading == '1') { 
     alert('Stop loading'); 
     return false; 
     } 
    } 
1

聲明你在父範圍變量: VAR stop_loading = '0';

$.get("/new/verify.php", { username: username, email: email }, 
    function(data){ 

     if(data == 'username') 
     { 
      alert('username taken'); 
      $('#username_taken_error').show(); 
      $('#username').focus(); 
      stop_loading = '1'; 
     }else if(data == 'email') { 
      alert('email taken'); 
      $('#email_taken_error').show(); 
      $('#email').focus(); 
      stop_loading = '1'; 
     }else if(data == 'username|email') { 
      alert('username/email taken'); 
      $('#username_taken_error').show(); 
      $('#email_taken_error').show(); 
      $('#username').focus(); 
      stop_loading = '1';  
     } 
}); 

alert(stop_loading); 

if(stop_loading == '1') { 
    alert('Stop loading'); 
    return false; 
} 
+0

酵母我嘗試添加該變量的準備功能以外,將它添加到get函數以外,當然也會將其添加到內部,但每次我提醒該值爲空時。 – Glen 2012-07-28 08:33:34

+0

請參閱codeparadox的評論。這就是你需要的。 – AdityaParab 2012-07-28 10:03:24