1

我正在从 facebook 上的游戏中提取数据并将这些值存储在一个对象中,然后将其传递给 PHP 页面。除了存储在对象中的值没有被分配给全局对象变量之外,一切正常。

如果我打印出函数中每个键的值,一切都很好。但是,如果我在函数外部打印它们,它们会返回 null,但在函数外部分配的键值除外。

var myObj={};
var key, val, i, nxtCell;
var srcStrings=["Attack","Defense","Health","Energy","Stamina"];

$.ajax(
{
type:'GET',url:'<game link'+uID,
dataType:'html',
success:function(data)
{
    var table=$(data);
    var myTD=table.find("td");

    $(myTD).each(function()
    {


        for(i=0;srcStrings.length>i;i++)
        {
            if($(this).text().indexOf(srcStrings[i])>=0 && $(this).text().indexOf("by")<0)
            {

                key=$.trim($(this).text());
                key=key.replace(':','');
                val=$.trim($(this).closest("td").next().text());                
                myObj[key]=val;




            }
        };
    });

            // This print works fine.
    $.each(myObj, function(key, value)
    {
        console.log(key + ":" + value);
    });

}
});

// Printing myObj key -> value pairs does not work here.

正如我所说,最后每个函数打印出对象值。但它们不会在 AJAX 回调之外打印出来。我尝试将数据传递给 AJAX 调用之外的函数以查看是否有任何效果,但它没有。

4

1 回答 1

2

This is because when you try and print the values outside of your AJAX callback function, myObj is still just an empty Object (besides any keys/values you set for it explicitly).

E.G.

var myObj = {};
$.ajax({
  // Settings and callback function that manipulates myObj
})

// Code to print myObj Key -> Value pairs

All of this code is run serially, and since your AJAX call has not returned by the time you are printing myObj, it doesn't have the values that you are expecting.

于 2013-07-23T17:00:20.343 回答