Javascript Jquery Ajax回调外部函数
所以这个函数工作得很好,除了我还有六个按钮,我不希望我的代码有太多的重复代码,那么有没有办法拉出beforeSend调用并使其成为一个外部回调函数?先谢谢你Javascript Jquery Ajax回调外部函数,javascript,jquery,ajax,coffeescript,Javascript,Jquery,Ajax,Coffeescript,所以这个函数工作得很好,除了我还有六个按钮,我不希望我的代码有太多的重复代码,那么有没有办法拉出beforeSend调用并使其成为一个外部回调函数?先谢谢你 $('#button_status').on 'click', -> username = $('#login_username').val() password = $('#login_password').val() mac_id = $('#login_mac').val() $.ajax type: "GET" ur
$('#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"
您不能将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
当然
只需确保变量是作用域的一部分。CoffeScript是函数作用域。还需要注意的是,此代码是用CoffeScript编写的。beforeSend:onBeforeSend将无法使用CoffeScript。未定义的函数是我的错误,但@beautifulcoder是正确的。谢谢!我会投赞成票,但遗憾的是我没有足够的分数。但我会接受它,只要你能选择它作为答案。还有一件事,分号不属于coffescript。我会更新我的答案。你介意帮我用这个错误函数创建一个可自定义的回调吗?
callback = (xhr) -> xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password))
beforeSend: callback