簡體   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