开发者

Global Var Javascript

开发者 https://www.devze.com 2023-03-31 10:02 出处:网络
I have an function in JavaScript, I try to change an global var from an function but always returns the same initial value 3:

I have an function in JavaScript, I try to change an global var from an function but always returns the same initial value 3:

For example: start value 3, function value 0, but always aler开发者_如何学Got 3.

    var test = 3;
    jQuery.ajax({
         type: "POST",
         url: "ajax_js.php",
         data: String,
         success: function(result){
            test = result;
              if(result == 0){
                 $('input[name=user_name]').val('');
                 }
          }
     });
     alert( test);


The A in Ajax means asynchronous.

Your alert is being called before the request is finished, before success is called and has a chance to update the variable.

Try to move the alert into the callback function and see if that works.


put your var test = 3; outside of the function eg:

<script type="text/javascript">
var test = 3;
$('#button').click(function() {
jQuery.ajax({
     type: "POST",
     url: "ajax_js.php",
     data: String,
     success: function(result){
        test = result; 
        alert( test);
          if(result == 0){
             $('input[name=user_name]').val('');
             }
      }
 });
});

</script>
0

精彩评论

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

关注公众号