开发者

jQuery: $.ajax inside if-statement allways called (should not!)

Good Morning everybody


EDIT: Sorry bout the written mistakes! The idea was to show a minimal example and i tipped it specially in here. But the main idea should be understandable.

I also tried to store the "outer" ajax result into an array. That works fine but the problem is the same. I guess that the problem is the asynchronouse handling of the different ajax calls. Because of that i get the result sometimes "twice" instead of two different results and i get the result too late.

I guess that i have to use the queue ore something like this.

I have a problem with my jQuery script. The minimal looks something like this:

// - First call "outer" .ajax
$.ajax({
  type: "GET", url: "FILE.xml", dataType: "xml",
  success: function( outerxml ) {

    $( outerxml ).find("content").each( function() {

      var x = $(this).attr('id'); // - Get id attribute
      if ( x == 'doit' )
      {
        $.ajax({
          type: "GET", url: "FILE.xml", dataType: "xml",
          success: function( innerxml ) {
             alert("inner ajax");
             ...
          } // - End of inner success
        }); // - End of inner .ajax
      }
      alert("end of if statement");

    }); // - End .find("content")

  } // - End outer success
}); // - End outer .ajax

Please note that the if-condition is "false" (x != "doit"). The problem is that the script runs to the end of the if-statement (i get the "end of if statement"-alert) and AFTERWARDS the script calls the ajax (but it should not). I get the "inn开发者_StackOverflow中文版er ajax"-alert after the "end of if statement" alert.

I cannot find a solution or the problem at all. Are there some hints? :) Please.

Thanks a lot!


You have an if statement on one line, and an opening brace on the next line. I think you're running into JavaScript's most evil "feature" here: automatic semicolon insertion.

Basically, you have

if ( x == 'doit' )
{
    // code
}

But it is being parsed as

if (x == 'doit'); // <-- note semicolon inserted here

// Now this block is logically disconnected from the if statement
{
    // code
}

The moral of the story is to be very careful about where you introduce line breaks in JavaScript code, because the language wants to treat end-of-line as end-of-statement whenever it can.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜