jquery - CoffeeScript:将 jQuery Ajax 调用的数据存储在变量中

标签 jquery ajax coffeescript

我正在使用 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/

相关文章:

angularjs - Angular 用户界面 : Unknown provider: dialogProvider

jquery - 使用 jQuery 和 jQueryui 设置日期选择器中的最小日期

jquery - Superfish 在 Concrete5 编辑模式中将悬停类添加到父项

javascript - Google 日历图表点击日期并重定向页面(URL 中包含日期)

coffeescript - 在 CoffeeScript 中的函数调用中将函数作为第一个参数传递

javascript - Marionette:基于路由正则表达式启动和停止模块

jquery - 在列表中使用 insertAfter 创建多个结果时出现问题

Safari 和 Chrome 中的 AJAX 对象?

JavaScript异步函数: callback not working

javascript - HTTP header 在 $.AJAX 调用中不起作用