A variable that is not writable in the internal function

$(document).ready(function() {
    state = 0;
    $('#btnlogin').click(function() {
        $.post("php/redirect.php", {
            Username : $('#qi').attr('value'),
            Password : $('#password').attr('value')
            }, function(data) {
            console.log('first'+state);
            state = 3;
            console.log('second'+state);
        });
        console.log('third'+state);
    });
});

First, I declared a global variable and set it to 0.
In the internal function, I want to set var to a different value, but my output will not be set to the (global) external var, it will be set as the local var. My other problem is the order in which I get the output.

Conclusion:

third0<br>
first0<br>
second3<br>
+3
source share
3 answers

This is because it console.log('third'+state);is out of call $.post(AJAX) and calls faster than the ajax response.

It seems you misunderstood that AJAX is asynchronous .

+1
source

, $.post , - .

, :

$.post("php/redirect.php", redirect.php , :

function(data) {
  console.log('first'+state);
  state = 3;
  console.log('second'+state);
}

:

console.log('third'+state);

- 0, third0.

ajax , , :

first0
second3

, , , , , script.

+1

:

. :

  • AJAX
  • 'third'+state

0, third0.

AJAX . 'first'+state. state 0, first0.

state , second3.

, , AJAX . , , .

0

All Articles