Coffeescript Ajax——不能让变量在函数之外工作

Coffeescript Ajax -- can't get variable to work outside of function?

本文关键字:函数 工作 变量 Ajax 不能 Coffeescript      更新时间:2023-09-26

所以我有这个coffeescript函数:

thestring = ""
$.get '/ajax/questions', (data) -> 
    counter = 0
    dataLength = data.length
    while counter < dataLength
        thestring += "<option value=test>it wont work</option>"
        counter++   
console.log(thestring)
$("#question"+(numfilters+1)).append thestring

在我的例子中,data是一个长度为2的数组的数组,(例如:[[hello,test],[hi,moretest]])。问题似乎是我的变量,"字符串",只在函数内部局部改变。当我试图记录值是什么时,我只是得到我最初分配给它的任何值(在本例中是空字符串)。我在这里尝试做的是根据从ajax请求接收到的数据将选项附加到动态生成的选择框。

这是一个异步函数,因此回调内部的代码将在 ajax请求完成后被留出执行,而顶层函数的其余部分将首先完成。只需将处理结果的代码移到回调函数中:

thestring = ""
$.get '/ajax/questions', (data) ->
    # The code here will be run *after* the ajax function completes
    # This is called a callback 
    counter = 0
    dataLength = data.length
    while counter < dataLength
        thestring += "<option value=test>it wont work</option>"
        counter++   
    console.log(thestring)
    $("#question"+(numfilters+1)).append thestring
# Any code after here will execute immediately 
#  (i.e., before the ajax function completes)
# So if you access `thestring` here, it will still be empty
console.log thestring

我知道为什么它没有附加到选择框。在异步调用中计算变量"numfilters"之前,它的值正在增加。为了解决这个问题,我在异步调用之前分配了一个名为"jaxfilters"的新变量,该变量取numfilters的任何值,并且不增加。