【问题标题】:Jquery Ajax Callback External FunctionJquery Ajax 回调外部函数
【发布时间】:2014-04-22 23:36:24
【问题描述】:

所以这个函数可以完美运行,希望我还有六个按钮,并且不希望我的代码有大量重复代码,那么有没有办法拉出 beforeSend 调用并使其成为外部回调函数?提前谢谢你

$('#button_status').on 'click', ->
username = $('#login_username').val()
password = $('#login_password').val()
mac_id = $('#login_mac').val()

$.ajax
  type: "GET"
  url: start_url + mac_id + "/status"
  dataType: "json"
  crossDomain: true
  cache: false

  beforeSend: (xhr) ->
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));

!更多问题!

这也是我的 ajax 的一部分,但如果我让所有按钮都具有相同的回调,则错误消息将是相同且毫无意义的。我可以为每个按钮定制这个吗?谢谢!

  error: (xhr, ajaxOptions, thrownError) -> 
    console.dir arguments
    console.log("*| Status ", xhr.status)
    console.log("*| Error", thrownError)
    console.log("*| Ajax", ajaxOptions)
    if (not username? or not password?)
      $('#data-text').empty()   
      $('#data-text').append ("""<h1>Please Log In</h1>""")
      $('#input_username').fadeTo(100, 0.1).fadeTo(200, 1.0);
      $('#input_password').fadeTo(100, 0.1).fadeTo(200, 1.0);
      $('#header_user').css "background-color": "#d34242"
      $('#header_password').css "background-color": "#d34242"
      $('#data-text').css "background-color": "#d38642"
    else
      $('#data-text').empty()   
      $('#data-text').append ("""<h1>Failed Log In</h1>""")
      $('#input_username').fadeTo(100, 0.1).fadeTo(200, 1.0);
      $('#input_password').fadeTo(100, 0.1).fadeTo(200, 1.0);
      $('#header_user').css "background-color": "#d34242"
      $('#header_password').css "background-color": "#d34242"
      $('#data-text').css "background-color": "#d38642"

【问题讨论】:

  • 另外需要注意的是,这段代码是用 CoffeeScript 编写的。

标签: javascript jquery ajax coffeescript


【解决方案1】:

当然

callback = (xhr) -> xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password))
beforeSend: callback

只要确保变量是作用域的一部分。 CoffeScript 是函数范围的。

【讨论】:

  • 谢谢!这行得通,我会投票,但遗憾的是我没有足够的积分。但我会很快接受的
  • 您可以选择它作为答案。还有一件事,分号不属于咖啡稿。我会更新我的答案。
  • 您介意帮助我使用这个错误函数来创建可自定义的回调吗?
【解决方案2】:

你不能把 beforeSend 变成一个函数吗?

var onBeforeSend = function(xhr) {
     xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
}

然后做:

$.ajax
  type: "GET"
  url: start_url + mac_id + "/status"
  dataType: "json"
  crossDomain: true
  cache: false,
  beforeSend: onBeforeSend

这不是coffeescript,但这就是我使用普通javascript的方式。

这样的东西有用吗?

onBeforeSend = (xhr) ->
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));

$.ajax '/Foo/Bar/',
    type: "GET"
    url: start_url + mac_id + "/status"
    dataType: "json"
    crossDomain: true
    cache: false,
    beforeSend: (xhr) ->
        onBeforeSend xhr

【讨论】:

  • beforeSend: onBeforeSend 遗憾的是不能与咖啡脚本一起使用。
  • 未定义函数是我的错误,但@beautifulcoder 是正确的。
猜你喜欢
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多