Why is my Array behaving differently outside of an AJAX function? (populating jsTree) [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-02 20:04:44

问题


Long story short, I'm creating a JSON-like array for jsTree. What I don't understand is why the array is perfect for my needs inside the AJAX success function, but broken outside of that function. Check out the screenshot from my console dump, you can see the differences. Why is it different inside of the function vs. outside of the function?

Essentially, I can't do what I need to do unless it's in the perfect format: (myAry inside the function)

What gives, man?

var myAry = [];

$.ajax({
type: "GET",
url: "parents.xml",
dataType: "xml",
success: function(xml) {

    $(xml).find('group').each(function() {

      myAry.push({
        "id": $(this).find('GroupID').text(),
        "parent": "#",
        "text": $(this).find('GroupName').text(),
      });


    }); //end each loop

      //this array is PERFECT
      console.log(myAry);

      } //end success function
  }); //end ajax GET

  //THIS ARRAY IS BORKED
  console.log(myAry);

xml:

 <groups>
    <group>
        <GroupID>1</GroupID>
        <GroupName>Instructional Assistant</GroupName>
    </group>
    <group>
        <GroupID>2</GroupID>
        <GroupName>Technician</GroupName>
    </group>
    <group>
        <GroupID>3</GroupID>
        <GroupName>HR Specialist</GroupName>
    </group>
</groups>


回答1:


it hits this line of code 1st;

//THIS ARRAY IS BORKED console.log(myAry);

Asynchronous Javascript before the Ajax call returns processes



来源:https://stackoverflow.com/questions/47189964/why-is-my-array-behaving-differently-outside-of-an-ajax-function-populating-js

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