0

我确信我遗漏了一些明显的东西,但无论是什么,我似乎都无法弄清楚。

这是我所拥有的

var warr = new Array();

$('#step3next').click(function() {
    $.post('AJAX_GetGameWords.asp',function(data) {
        fw(data.warray);
    },"json");

    $('.vardisplay3').append(warr+'');
});

function fw(x) {
    warr = [x]; 
}

最终,我想要的是能够在任何地方使用 warr 阵列。

如果我把$('.vardisplay3').append(warr+''); fw(data.warray); 然后它就可以正常工作并显示在 .vardisplay3 中,但是在现在的位置上,它什么也不显示。

我认为由于 warr 被设置为全局,它会起作用,但我显然错过了范围问题或其他东西。

谁能解释发生了什么以及我如何能够在任何地方使用warr阵列。

谢谢

4

3 回答 3

3

It's not a scope issue, it's an order of execution issue. .post() is asynchronous, so this line of code:

$('.vardisplay3').append(warr+'');

is being executed before this line of code:

fw(data.warray);

The scope is fine, but if you want something to happen in response to an asynchronous AJAX call (such as appending a returned value) then it needs to be invoked from the call-back function of that AJAX call. Otherwise it'll execute before the AJAX call is finished and it won't have any data to use.

于 2013-05-07T16:37:06.833 回答
2

post is asynchronous.

you need to use the success callback if you want to use the returned data

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

于 2013-05-07T16:37:14.230 回答
0

您可以使用这样的ajax调用更改 $.post ,它将轻松回调您的数据并防止您出现此问题...

$.ajax({
  type: "POST",
  url: "AJAX_GetGameWords.asp",
  data: "",
  async: false,
  success: function(t){
    alert(t);// You can call your function HERE
  }
});  
于 2013-05-11T09:02:52.753 回答