开发者

js how to make my array be visible by other functions

my first alert shows the list of items but the second is not. I've never done anything in ajax/js before so i don't know how to return my array so it would be visible by other functions.

var mycarousel_itemList = [];

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "xml/images.xml",
        dataType: "xml",
        success: function (xml) {

            $(xml).find('image').each(function () {
                var id = $(this).attr('id');
                var url = $(this).find('url').text();
                mycarousel_itemList.push('{url:"' + url + '",' + 'id:"' + id + '"}');

                alert(mycarousel_itemList);
            });
        }
    });
    alert(mycarousel_itemList);
});

This is how my xml looks like

<images>
  <image id="1">
    <title>item</title>
    <url>images/image.gif</url>
    <desc>description of an item</desc>
  </image>
  <image id="2">
     <title>ano开发者_如何学编程theritem</title>
    <url>images/images.gif</url>
    <desc>description of an item</desc>
  </image>
</images>


The mycarousel_itemList array is not declared within a function and thus is global. You should be able to access the array in your success event function.

There's something borked with your specific example (e.g., the success function isn't getting hit because the server doesn't respond).

If I copy and paste your code and simply replaced the server-side component with a JSONP service (just so I can do AJAX across domains), I have no problem accessing the array:

var mycarousel_itemList = [];

$(document).ready(function () {
    var url = "http://github.com/api/v2/json/user/show/yui";
    $.ajax({
        type: "GET",
        url: url,
        dataType: "jsonp",
        success: function (data) {
                mycarousel_itemList.push(data.user.company + ' - ' + data.user.blog);
                alert(mycarousel_itemList[0]);
        }
    });
});

You can test it out here.


To answer the direct question: it's not possible to make the array populated when the second alert is called because by that time the AJAX call didn't have time to complete.

What function exactly need that array?

Just call it from within the success method after you populate the array and it will work just fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜