简体   繁体   English

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

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

So i have this coffeescript 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

in my case, data is an array of arrays of length 2, (ex: [[hello,test],[hi,moretest]] ). 就我而言,数据是长度为2的数组的数组(例如:[[hello,test],[hi,moretest]])。 The problem seems to be that my variable, "thestring", is only changed locally inside the function. 问题似乎是我的变量“ thestring”仅在函数内部局部更改。 When I attempt to log what the value is, i simply get whatever i initially assigned it (in this case the empty string). 当我尝试记录值是什么时,我只是得到最初分配的值(在这种情况下为空字符串)。 What I'm trying to do here is append options to a dynamically generated select box based on the data received from the ajax request. 我要在此处执行的操作是基于从ajax请求接收的数据将选项附加到动态生成的选择框。

This is an asynchronous function, so the code inside the callback will be set aside to be executed after the ajax request completes, and the rest of the top level function completes first. 这是一个异步函数,因此回调函数中的代码将被搁置,以便 ajax请求完成之后执行,而其余的顶层函数将首先完成。 Just move your code for handling the result inside of the callback function: 只需在回调函数内部移动代码以处理结果即可:

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

I figured out why it wasn't appending to the select box. 我弄清楚了为什么它没有追加到选择框。 The variable "numfilters" was getting increased before it was evaluated in the asynchronous call. 在异步调用中对变量“ numfilters”进行评估之前,变量已被增加。 To solve this i assigned a new variable called "jaxfilters" right before the asynchronous call, which takes whatever value that numfilters has and is not increased. 为了解决这个问题,我在异步调用之前分配了一个名为“ jaxfilters”的新变量,该变量采用numfilters具有但不增加的任何值。

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

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