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
在我的例子中,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的任何值,并且不增加。
相关文章:
- onmouseout函数工作不正常
- 我无法使onmouseout函数工作
- Javascript”;结束”;函数工作不稳定
- HTML JavaScript,我如何能够通过给每个元素一个不同的Id来使用JavaScript使这个函数工作
- Javascript:onclick函数工作一次,页面就会恢复到原来的状态
- jQuery toggle()函数工作不正常
- Node.js npm opn-can't使回调函数工作
- 添加两个数字的JavaScript函数工作不正常
- 调用在Jquery中未作为链接函数工作
- 将PHP变量传递给Javascript不能通过PHP函数工作(与全局变量无关)
- 为什么我需要在 javascript 函数工作之前按提交按钮 2 次
- 使 JavaScript 函数工作时遇到麻烦
- 如何使 clearInterval 函数工作
- 如何使 then 函数工作
- 如何让我的包含函数工作
- Promise.all 不应该作为传递给 .then 的函数工作
- 我无法让它作为 JavaScript 函数工作(我在控制台时得到我想要的返回值.log但我不能将其作为函数调用)
- JavaScript on change 函数工作得不好
- jquery next()函数工作不正常
- Jquery hasClass()函数工作不正常