2014-04-22 26 views
0

所以这个函数完美地工作,我有6个更多的按钮,不希望我的代码有大量的重复代码,所以有办法拉出beforeSend调用,并使其成为一个外部回调功能?提前致谢Jquery Ajax回调外部函数

$('#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)); 

!More to Question!

我有这也是我的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" 
+1

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

回答

0

当然

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

只要确保变量范围的一部分。 CoffeScript的功能范围。

+0

谢谢!这工作,我会投票,但可悲的是我没有足够的分数。但我会尽快接受 – TheAce

+0

您可以选择它作为答案。还有一件事,分号不属于coffescript。我会更新我的答案。 – beautifulcoder

+0

你介意帮助我使用这个错误函数来创建一个可定制的回调? – TheAce

0

你不能把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 
+0

beforeSend:onBeforeSend 不会悲伤地使用coffeescript。 – TheAce

+0

未定义函数是我的错误,但@beautifulcoder是正确的。 – TheAce