[英]Jquery Ajax Callback External Function
So this function works perfectly expect I have six more buttons and do not want my code to have a ton of repeat code, so is there a way to pull out the beforeSend call and make it an external callback function? 因此,此功能可以正常运行,希望我还有六个按钮,并且我的代码不希望有大量重复代码,因此,有没有办法撤出beforeSend调用并使其成为外部回调函数? Thank You In Advance
先感谢您
$('#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! !更多问题!
I have this also part of my ajax but if I make all buttons have the same callback the error messages will be the same and pointless. 我的ajax也有这个部分,但是如果我使所有按钮都具有相同的回调,则错误消息将是相同且毫无意义的。 I can I make this customizable for each button?
我可以使每个按钮自定义吗? Thank You!
谢谢!
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"
Could you not turn the beforeSend into a function? 您不能将beforeSend转换为功能吗?
var onBeforeSend = function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
}
and then do: 然后执行:
$.ajax
type: "GET"
url: start_url + mac_id + "/status"
dataType: "json"
crossDomain: true
cache: false,
beforeSend: onBeforeSend
It's not coffeescript, but that's how I would do it with plain javascript. 它不是coffeescript,但这就是我要用纯JavaScript做到的方式。
Would something like this work? 这样的事情行吗?
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
Sure 当然
callback = (xhr) -> xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password))
beforeSend: callback
Just make sure variables are part of the scope. 只要确保变量是范围的一部分。 CoffeScript is function scoped.
CoffeScript具有功能范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.