繁体   English   中英

Coffeescript Ajax-无法使变量在函数外部工作吗?

[英]Coffeescript Ajax — can't get variable to work outside of function?

所以我有这个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

就我而言,数据是长度为2的数组的数组(例如:[[hello,test],[hi,moretest]])。 问题似乎是我的变量“ thestring”仅在函数内部局部更改。 当我尝试记录值是什么时,我只是得到最初分配的值(在这种情况下为空字符串)。 我要在此处执行的操作是基于从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具有但不增加的任何值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM