如何使用coffeescript制作$ .get请求?

Tum*_*Tum 24 jquery coffeescript

如何在CoffeeScript中执行以下操作?

  $( function() {
    $('input#username').keyup( function() {
      var username = $('input#username').val();
      url = '/users/check_username/';
      params = { username : username };
      $.get(url, params, function(response){ markUsername(response); }, "json");
    });
  })
Run Code Online (Sandbox Code Playgroud)

jas*_*nas 33

这是另一种略微浓缩的方式来编写它:

$ ->
  $('input#username').keyup ->
    username = $(this).val()
    callback = (response) -> markerUsername response
    $.get '/users/check_username/', {username}, callback, 'json'
Run Code Online (Sandbox Code Playgroud)

请注意缺少parens和简写"{username}"对象文字.

  • 这是在CoffeeScript中编写它的不错的规范方法 - 来自为您带来CoffeeScript的人!这个例子说明了一些CoffeeScript的功能,我认为这些功能使CoffeeScript成为一种很好用的小语言. (2认同)

ben*_*ich 16

这是我到目前为止提出的最好的通用模式:

$.ajax '/yourUrlHere',
  data :
    key : 'value'
  success  : (res, status, xhr) ->
  error    : (xhr, status, err) ->
  complete : (xhr, status) ->
Run Code Online (Sandbox Code Playgroud)

它编译为:

$.ajax('/yourUrlHere', {
  data: {
    key: 'value'
  },
  success: function(res, status, xhr) {},
  error: function(xhr, status, err) {},
  complete: function(xhr, status) {}
});
Run Code Online (Sandbox Code Playgroud)