我正在使用 CoffeeScript 和 jQuery,尝试从存储在本地变量中的 ajax 调用获取数据,以便我可以在方法的其余部分中使用它。这是我现有的代码:
response = null
$.ajax
url: '/polygons'
dataType: 'json'
success: (data, textStatus, jqHXR) ->
response = data
console.log response
使用此代码,响应始终保持为空。我想做的就是将数据变量从 success 函数中取出并放入调用方法中,但我似乎无法将其移出该范围。我在这里做错了什么?
最佳答案
Ajax 是异步的,因此调用 console.log response
时不会设置响应,请在回调函数中使用响应。
response = null
$.ajax
url: '/polygons'
dataType: 'json'
success: (data, textStatus, jqHXR) ->
response = data
console.log response
<小时/>
how do I make sure the script waits after this until the ajax call is complete, so it won't proceed using the null response object?
您应该在回调函数中完成所有处理,如果您不想这样做,可以通过在 ajax 选项中将 async 更改为 false 来使 ajax 调用同步
关于jquery - CoffeeScript:将 jQuery Ajax 调用的数据存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12240193/