I'm still learning JQuery (and as a result a little JavaScript) but I can't seem to find out how to use a previously defined function in a callback.
Say I have:
<script>
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
});
</script>
And I wish to use this in another function e.g:
<script>
$(document).ready(function() {
$.ajax({
beforeSend: ajax_start(),
url: "insert_part.php",
type:"POST",
开发者_StackOverflow社区 data: "customer="+customer
});
});
</script>
Would this be correct? (I assume not as it doesn't...) what is the proper way of doing a callback?
Close.
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
$.ajax({
beforeSend: ajax_start, // <== remove the parens
url: "insert_part.php",
type:"POST",
data: "customer="+customer // <== as Skilldrick pointed out,
// remove the trailing comma as well
});
});
You need to do this because
ajax_start()
evaluates to the value returned by executing the function namedajax_start
, butajax_start
evaluates to the function itself.
Edit re: OP comment
"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"
There are a couple ways to do it. Combine them using an anonymous function:
$.ajax({
// if you need the arguments passed to the callback
beforeSend: function (xhr, settings) {
ajax_start();
other_function();
},
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
Or just declare a named function that does what you want, and then use it:
function combined_function(xhr, settings) {
ajax_start();
other_function();
}
$.ajax({
beforeSend: combined_function,
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
Change the value of beforeSend
to ajax_start
. In other words, remove the parentheses.
With the parentheses, you're calling ajax_start()
and setting beforeSend
to the return value of ajax_start()
(in this case, I believe that would be undefined
).
just remove the parentheses, then you are referencing the 'function'-object. The () calls the function, so you would pass the return value of ajax_start.
$.ajax({
beforeSend: ajax_start,
url: "insert_part.php",
type:"POST",
data: "customer="+customer,
});
});
精彩评论