Coffeescript中Ajax请求的返回结果
我仍在了解 CoffeeScript 并了解它的能力。
我已经编写了一个进行 ajax 调用的方法,并且我想返回结果。
例如:
GetViewedItem: (foo) ->
$.ajax '/Foo/Bar/',
type: 'GET',
data: { id: $(foo).data('fooId') }
success: (data) ->
data
我想返回数据。在 CoffeeScript 中是否有一种聪明的方法可以做到这一点,或者我只需要声明一个变量?
谢谢
Still getting my head around CoffeeScript and and seeing what its capable of.
I've written a method that makes a ajax call and I'm wanting to return the results.
For example:
GetViewedItem: (foo) ->
$.ajax '/Foo/Bar/',
type: 'GET',
data: { id: $(foo).data('fooId') }
success: (data) ->
data
and I want to return data. Is there a clever way of doing this in CoffeeScript or do I just have to declare a variable?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上无法以这种方式返回 AJAX 请求上的数据,因为它是异步的。这意味着,当成功回调被调用时,您的 GetViewedItem 方法将完成执行。
通常,您将继续在成功回调中对 AJAX 数据执行任何需要执行的操作,或者从成功回调中调用相应处理数据的方法。
这可能是使用 JS 和 AJAX 时需要理解的最重要的概念之一。
You can't really return the data on an AJAX request that way since it is asynchronous. Meaning, by the time the success callback is called, your
GetViewedItem
method will have finished executing.Normally, you would continue doing whatever you need to do with the AJAX data in the success callback or call a method from the success callback that deals with the data accordingly.
This is probably one of the most important concepts to understand when using JS and AJAX.
正如已经提到的,这与浏览器中的异步性质 javascript 有关。 CoffeeScript 有一个“补丁”可以直接处理这个问题(添加 async/defer),请参阅 http:// maxtaco.github.com/coffee-script/ 。对于你的例子,它会是这样的(根据我对它的理解,我这边猜测):
还有许多其他 javascript 库也可以用于类似的目的。但请注意,当脚本等待数据时,浏览器可能会出现“挂起”状态(不确定“defer”函数是否继续处理 javascript 事件)。
As mentioned already, this has to do with the async nature javascript in the browser. There's "a patch" to CoffeeScript that deals with this directly (adding async/defer), see http://maxtaco.github.com/coffee-script/ . For your example, it would be something like (guesswork on my side based on my understanding of it):
There are numerous other javascript libraries as well which can also be used for similar purposes. But be aware that the browser may appear "hung" while your script is waiting for data (not sure if the "defer" function keep handling javascript events or not).