0

我正在使用 jQuery $.getJSON(..) 来获取一些 json。

传递的值向我显示"undefined"

有没有办法做到这一点?

getTopMenuJson : function(currentPage) {
    if(currentPage == null) currentPage = 1;

    var retJSON;

    $.getJSON(
            requestURLs.topMenuJson, 
            {
                'ITEM_PER_PAGE' : TopMenuHandler.ITEM_PER_PAGE,
                'CURRENT_PAGE' : currentPage
            },
            function(JSON) {
                //alert(JSON); **<--This gives me result (Object)**
                retJSON = JSON;
            }
    );

    **alert(retJSON); //<!-- This doesn't, but Undefined**
},
4

1 回答 1

1

它没有也不应该像getJSON在内部进行 AJAX 调用一样,AJAX 中的第一个A代表Asynchronous,它只是意味着脚本执行不会等到success调用你的函数。

您可以改为使用$.ajax并传入async: false其中一个选项,以确保您的脚本等待 ajax 调用完成,但请注意,这样做会冻结浏览器/选项卡,直到您的 AJAX 调用完成。

$.ajax({
  url: requestURLs.topMenuJson,
  dataType: 'json',
  data:  
  {
     'ITEM_PER_PAGE' : TopMenuHandler.ITEM_PER_PAGE,
     'CURRENT_PAGE' : currentPage
  },
  success: function(JSON) {
     //alert(JSON); **<--This gives me result (Object)**
     // this won't work without async:false
     // as the execution of script won't wait until this function 
     // is finished
     retJSON = JSON; 
  },
  async: false
});

http://api.jquery.com/jQuery.ajax/

async 默认值:true 默认情况下,所有请求都是异步发送的(即默认设置为 true)。如果您需要同步请求,请将此选项设置为 false。跨域请求和 dataType: "jsonp" 请求不支持同步操作。 请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。

于 2012-05-11T02:20:30.143 回答